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.
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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With