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

.net entity-framework

Question

I am inserting data in multiple tables. I need to know the last inserted (auto-incremented) ID in the table. I need to use it as a Foriegn Key in some other table.

In short I need alternative of @@Identity in T-Sql.

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

Accepted Answer

Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:

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

context.AddObject(customer);

context.SaveChanges();

var id = customer.Id;

Note that the Id property only gets populated after calling SaveChanges() in case the StoreGeneratedPattern attribute is set to "Identity" or "Computed" for the auto-incremented ID column in the Storage part of the model.

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

Popular Answer

Anyhow if you need the the id for some any other purpose ... calling EF Insert Method for some entity automatically returns the currently inserted row id ...

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