Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Find in CodeFirst (EntityFramework) to get non-primary keys

My understanding is that find only takes the primary key as the parameter. That works great if the value you are looking for is actually the primary key. In my case, I have a class like this:

 public class Chamber
 {
    [Key]
    public int Id {get;set;}

    public string ChamberName { get; set; }
 }

I want to check whether a given ChamberName exists in either my context or the database itself. How can I do that? Do I have to somehow enumerate of the context myself first, then, look it up in the database with a call like db.Chambers.where(a=>a.ChamberName.equals...?

I can see it working well if ChamberName is my primary key, but it is not.

THanks,

like image 603
Peter Kellner Avatar asked Dec 01 '25 13:12

Peter Kellner


1 Answers

There is a property called Local in the DbSet. You can query that first to find entities loaded to the context.

var entity = db.Chambers.Local.Where(/**/).SingleOrDefault();

if (entity == null)
{
   entity = db.Chambers.Where(/**/).SingleOrDefault();
}
like image 117
Eranga Avatar answered Dec 04 '25 13:12

Eranga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!