Reputation: 9017
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
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
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