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.
-
yes but What I want is simply "select * from Customer where custId=2"– saurabhDec 4, 2011 at 14:52
5 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();
-
2I was expecting just simple function call for example customerobject.getbjectByID()– saurabhDec 4, 2011 at 14:55
-
Well, you could build a Extention Method and try to make the Lambda generic, maybe with an interface or something similar. Otherwise I am very pessimistic about it.– JannikDec 7, 2015 at 6:24
"instead of lambda expression or query"
customerobject.Find(id);
More specifically:
var myDbSetTableEntity = context.MyDbSetTableEntity.Find(object key1, object key2)
The most compact way:
var myCustomer = myContext.Customers.SingleOrDefault(c => c.Id == wantedId);
wich is basically short-form for
myContext.Customers.Where(c => c.Id == wantedId).SingleOrDefault();
Other candidate selection methods are Single(), First() and FirstOrDefault()
-
Good to note that the short-form requires an import of System.LINQ by stating
using System.Linq;
Nov 8, 2021 at 11:26
If you have a composite key, build an object array and pass it to Find(). Eg:
try
{
RECORD rec; // ie, your entity definition of a record (row)
Object[] onePK = { id, s0, s1 };
rec = YourEntities.RECORDs.Find(onePK);
if (rec == null)
{
// handle the record-not-found situation
}
}
catch (SystemException sex)
{
string error = sex.Message;
}
for composite keys: customerobject.Find(key1, key2, key3)
what is order you specify the keys, assuming they are all strings ?