user194076
user194076

Reputation: 9017

Get item from entity framework by ID

Simple question. I have entity Customer in my edmx model. I need to get the customer with Id = 20 in c#. How do I do that?

Upvotes: 10

Views: 30834

Answers (3)

Zorayr
Zorayr

Reputation: 24922

You could also use a LINQ approach, as follows:

Customer customerRecord = 
    (from customer in Entities.Customers
     where customer.id == 20
     select customer).FirstOrDefault();

Using FirstOrDefault() will return null if the element with that ID doesn't exist, as opposed to First() which will throw an exception. Also, make sure to include, using System.Linq; before using LINQ statements.

Hope this helps.

Upvotes: 1

Jared S
Jared S

Reputation: 3416

You'll want to use .First() or .FirstOrDefault(). The difference comes down to whether you want a null or an exception in the case that your customer does not exist.

The .First() method will throw an exception if there are no matching results in the database. The .FirstOrDefault() method will return null if there are no matching results in the database

Customer customer21 = oe.Customers.First(c => c.CustomerId == 20); // throws an exception if customer 21 does not exist

Customer customer21 = oe.Customers.FirstOrDefault(c => c.CustomerId == 20); // null if customer 21 does not exist

Upvotes: 10

agent-j
agent-j

Reputation: 27913

Entities.Customer.First(c => c.CustomerId == 20);

Upvotes: 24

Related Questions