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.
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.
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();
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.
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.
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.
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);
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