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?
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();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With