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?
According to Entity Framework the solution is:
using (var context = new EntityContext())
{
var customer = new Customer()
{
Name = "John"
};
context.Customers.Add(customer);
context.SaveChanges();
int id = customer.CustomerID;
}
This doesn’t get the database table identity, but gets the assigned ID of the entity, if we delete a record from the table the seed identity will not match the entity ID.
1Best Answer
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.Add(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.