In Entity Framework, how do I retrieve the Id of an entered entity?

c# entity entity-framework

Question

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?

1
604
5/7/2014 1:00:31 PM

Popular 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 Ids are used.

988
11/30/2019 5:31:45 PM


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