Entity Framework 4 getting primary key ID for inserted record

.net c# entity-framework

Question

I am using the Entity Framework for inserting a row into my sql database. If I was to be using a stored procedure then I would be able to return the primary key for the record which I had inserted.

Am I able to do return the PK for the last my last record inserted using the Entity Framework?

1
35
6/24/2011 10:56:46 AM

Accepted Answer

After you have inserted the entity it should have been updated so that the property that maps to the primary key in the database has the new PK value.

40
6/24/2011 10:02:29 AM

Popular Answer

Yes of course you can do this. See example:

int id = 0;

using (PC2Entities objectContext = new PC2Entities())
{
   objectContext.ClientContacts.AddObject(clientContact);
   objectContext.SaveChanges();
   id = clientContact.Id;

   transaction.Complete();
}

id is the PK.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow