How can I get Id of inserted entity in Entity framework?
I have a problem with Entity Framework in Asp.net. I want to get the Id value whenever I add an object to database. How can I do this?
It is pretty easy. If you are using DB generated Ids (like IDENTITY
in MS SQL) you just need to add entity to ObjectSet
and SaveChanges
on related ObjectContext
. Id
will be automatically filled for you:
using (var context = new MyContext())
{
context.MyEntities.AddObject(myNewObject);
context.SaveChanges();
int id = myNewObject.Id; // Yes it's here
}
Entity framework by default follows each INSERT
with SELECT SCOPE_IDENTITY()
when auto-generated Id
s are used.
I had been using Ladislav Mrnka's answer to successfully retrieve Ids when using the Entity Framework however I am posting here because I had been miss-using it (ie using it where it wasn't required) and thought I would post my findings here in-case people are looking to "solve" the problem I had.
Consider an Order object that has foreign key relationship with Customer. When I added a new customer and a new order at the same time I was doing something like this;
var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id
However in my case this was not required because I had a foreign key relationship between customer.Id and order.CustomerId
All I had to do was this;
var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer};
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order
Now when I save the changes the id that is generated for customer is also added to order. I've no need for the additional steps
I'm aware this doesn't answer the original question but thought it might help developers who are new to EF from over-using the top-voted answer for something that may not be required.
You need to reload the entity after savechanges. Because it has been altered by a database trigger which cannot be tracked by EF. SO we need to reload the entity again from the DB,
db.Entry(MyNewObject).GetDatabaseValues();
Then
int id = myNewObject.Id;
Look at @jayantha answer in below question:
How can I get Id of inserted entity in Entity framework when using defaultValue?
Looking @christian answer in below question may help too:
Entity Framework Refresh context?
链接地址: http://www.djcxy.com/p/5732.html上一篇: 在实体框架中插入的最快方式
下一篇: 我如何获得实体框架中插入的实体的Id?