Reputation: 540
I have a table "Customer" and its corresponding ORMapping Entity Customer in entity framework and I want to find an object corresponding to a given primary key.
Something like customerObject.getObjectByID()
instead of a lambda expression or query.
Upvotes: 10
Views: 24182
Reputation: 412
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;
}
Upvotes: 2
Reputation: 933
"instead of lambda expression or query"
customerobject.Find(id);
More specifically:
var myDbSetTableEntity = context.MyDbSetTableEntity.Find(object key1, object key2)
Upvotes: 8
Reputation: 31
for composite keys: customerobject.Find(key1, key2, key3)
what is order you specify the keys, assuming they are all strings ?
Upvotes: 1
Reputation: 63970
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();
Upvotes: 12
Reputation: 273864
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()
Upvotes: 3