Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an identity of the last inserted row in Entity Framework?

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.

like image 993
Vaibhav Jain Avatar asked Nov 01 '10 10:11

Vaibhav Jain


People also ask

How do I get the last inserted row ID?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command.

How do I get the identity column value after INSERT in 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();

How do I get last inserted data?

you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it. Show activity on this post. For any last inserted record will be get through mysql_insert_id() If your table contain any AUTO_INCREMENT column it will return that Value.

How do you find the value of the last inserted identity column?

IDENT_CURRENT() will give you the last identity value inserted into a specific table from any scope, by any user. @@IDENTITY gives you the last identity value generated by the most recent INSERT statement for the current connection, regardless of table or scope.


2 Answers

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.

like image 197
Steven Avatar answered Sep 19 '22 07:09

Steven


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);  
like image 40
umer Avatar answered Sep 19 '22 07:09

umer