Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 getting primary key ID for inserted record

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?

like image 813
Matt Seymour Avatar asked Jun 24 '11 09:06

Matt Seymour


People also ask

How do I get an ID after inserting EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

How do I insert a record into Entity Framework?

Insert DataUse the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students.


2 Answers

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.

like image 184
Ben Robinson Avatar answered Sep 29 '22 11:09

Ben Robinson


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.

like image 34
asma Avatar answered Sep 29 '22 11:09

asma