Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object for given primary key in entity framework

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.

like image 594
saurabh Avatar asked Dec 04 '11 14:12

saurabh


People also ask

What is the method used to search for an entity object using a primary key value?

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.

What does DbSet do?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

How do I select specific columns in Entity Framework?

We can do that simply by using the “new” operator and selecting the properties from the object that we need. In this case, we only want to retrieve the Id and Title columns. There. That looks better.

What is DbContext and DbSet in entity framework core?

DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table.


2 Answers

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();
like image 101
Icarus Avatar answered Oct 04 '22 14:10

Icarus


"instead of lambda expression or query"

customerobject.Find(id);

More specifically:

var myDbSetTableEntity = context.MyDbSetTableEntity.Find(object key1, object key2)
like image 31
Dave Jellison Avatar answered Oct 04 '22 15:10

Dave Jellison