How can I get Id of inserted entity in Entity framework when using defaultValue?

28,269

Solution 1

You need to reload the entity after savechanges.Because it has been altered by a database trigger which cannot be tracked by EF. SO we need to reload the entity again from the DB,

var x = new Stuff();
db.Stuff.AddObject(x);
db.SaveChanges();
db.Entry(x).GetDatabaseValues();

return x.ID;

Solution 2

If you are using EF core it could be like this:

 public int CreateMyEntity(MyEntityType myEntity)
 {
      Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<MyEntityType> created = _context.MyEntityType.Add(myEntity);
      _context.SaveChanges()
      return created.Entity.Id;
  }

Solution 3

I had the same problem, that my key would not update after calling SaveChanges and it would only return null for context.Entry(newObj).GetDatabaseValues().

In my case, setting StoreGeneratedPattern to Identity (on the key) in the EntityFramework model caused the key to update after calling SaveChanges.

Solution 4

using (var context = new EntityContext())
{
    var customer = new Customer()
    {
        Name = "John"
    };

    context.Customers.Add(customer);

    context.SaveChanges();      

    int id = customer.CustomerID;
}

Solution 5

I'm using a data transfer object (DTO) to hide details of the data layer from the front end - then assigning values from it to the db object. My CustomerId is an identity which is automatically refreshed after SaveChanges() is called. No other method calls are needed. And since "customer" is a ref object, it is propagated to the front end.

public static void Add(DTO.Customer customer)
{
    MyEntities db = new MyEntities();

    var customerToAdd = new MyEntities.Data.Customer { Address = customer.Address, FirstName = customer.FirstName, LastName = customer.LastName, etc... };
    db.Customers.Add(customerToAdd);

    db.SaveChanges();
    customer.CustomerId = customerToAdd.CustomerId;
}
Share:
28,269
Jan Matousek
Author by

Jan Matousek

Updated on July 05, 2022

Comments

  • Jan Matousek
    Jan Matousek almost 2 years

    Is there a way to send a property with defaultValue but update it with the database computed result? There's a trigger in database, that for input -1 triggers a procedure which computes a new value. How to get the value back?

    <Property Name="ID" Type="int" Nullable="false" StoreGeneratedPattern="None" DefaultValue="-1" />
    
    var x = new Stuff();
    db.Stuff.AddObject(x);
    db.SaveChanges();
    return x.ID //gives -1, but the computed value should be different.