Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I retrieve Id of inserted entity using Entity framework? [closed]

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.

like image 847
ahmet Avatar asked Mar 06 '11 19:03

ahmet


People also ask

How do I get an ID after inserting EF core?

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 ID before SaveChanges?

You can retreive an ID before calling . SaveChanges() by using the Hi/Lo alhorithm. The id will be assigned to the object once it is added to dbcontext.

What does DB SaveChanges return?

Returns. The number of state entries written to the underlying database.


1 Answers

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.

like image 194
Ladislav Mrnka Avatar answered Sep 21 '22 08:09

Ladislav Mrnka