Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ID of recently created entity - ADO Entity Framework

Say you create an object and saving to database by using ADO Entity Framwork as in the code below.

private void CreateAddress(BizObjects.Address address)
{
    var entity = new EntityFramework.Address();

    entity.Line1 = address.Line1;
    entity.Line2 = address.Line2;
    entity.City = address.City;
    entity.State = address.State;
    entity.ZipCode = address.ZipCode;

    _entities.AddToAddress(entity);
    _entities.SaveChanges();
}

How can I retrieve the ID of the newly created object?

Thanks in advance.

like image 744
Guillermo Gomez Avatar asked Jan 02 '10 01:01

Guillermo Gomez


People also ask

How do I get my ID after SaveChanges?

Now, when you add a new Student and call SaveChanges() method, EF will assign a newly generated id to the StudentID property. 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.

How do I get the inserted record ID in Linq?

after inserting the record into database it returns your record with created Id. You don't need to call any other method to get the id, you already got that after successful insertion so check your object which you passed in you "InsertOnSubmit" method. Here Customers is your table name.

How do I get the last record of EF model data?

Answer: If you want to get the most recent record from the database using EF Core or Entity Framework then you must order the result then get FirstOrDefault() record from the dataset returned. See the code below: var MyRecentRecord = _context. MyDataModalOrPOCO.

Is Ado net faster than EF?

Performance: ADO.NET is much faster compared to the Entity Framework. Because ADO.NET always establishes the connection directly to the database. That's why it provides much better performance compared to the Entity Framework.


1 Answers

Once you call "SaveChanges()" the entity object should have the ID field filled by the framework.

private void CreateAddress(BizObjects.Address address)
{
    var entity = new EntityFramework.Address();

    entity.Line1 = address.Line1;
    entity.Line2 = address.Line2;
    entity.City = address.City;
    entity.State = address.State;
    entity.ZipCode = address.ZipCode;

    _entities.AddToAddress(entity);
    _entities.SaveChanges();

    address.Id = entity.Id; // At this point the entity object will have the value of the Id field.
}

Hope this helps...

like image 80
Lukasz Avatar answered Sep 17 '22 17:09

Lukasz