In Entity Framework, how can I get the identity of the last added row?

.net entity-framework

Question

I'm adding data to many tables. I need knowledge of the most recent (auto-incremented) ID entered into the database. It must be used as a foreign key in another table.

I just need an alternative to@@Identity using T-Sql.

1
40
11/1/2010 10:37:07 AM

Accepted Answer

To fill the main key column of the entered object, Entity Framework will automatically load the most recent inserted id:

var customer = new Customer { Name = "Steven" };

context.AddObject(customer);

context.SaveChanges();

var id = customer.Id;

Observe that theId property only get filled after a callSaveChanges() should theStoreGeneratedPattern attribute for the auto-incremented ID column in the Storage section of the model is set to "Identity" or "Computed."

88
7/8/2019 7:36:52 AM

Popular Answer

However, using an entity's EF Insert Method automatically returns the currently inserted row id if you require the ID for any other reason.

var rowId=db.Insert(Entity); 


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