Find object for given primary key in entity framework

saurabh picture saurabh · Dec 4, 2011 · Viewed 19.8k times · Source

I have a table "Customer" and it's corresponding ORMapping Entity Customer in entity framework and I want to find an object corresponding to a given primary key. Something like customerobject.getbjectByID() instead of lambda expression or query.

Answer

Icarus picture Icarus · Dec 4, 2011
var Customer = from c in datacontext.Customer
               where c.CustomerID == your_key
               select c;

That's assuming your customer table has a CustomerID column and that is the primary key.

Using DbSet's Find method:

Customer customer= db.Customer.Find(your_key);

Using a lambda expression:

 var customer= dataContext.Customer.Where(x=>x.CustomerID==your_key).FirstOrDefault();