Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get item from entity framework by ID

Tags:

c#

asp.net

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?

like image 286
user194076 Avatar asked Jul 13 '11 00:07

user194076


2 Answers

Entities.Customer.First(c => c.CustomerId == 20);
like image 166
agent-j Avatar answered Oct 04 '22 02:10

agent-j


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.

like image 42
Zorayr Avatar answered Oct 04 '22 04:10

Zorayr