How can I get Id of inserted entity in Entity framework when using defaultValue?
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.
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;
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
.
using (var context = new MyContext())
{
context.MyEntities.AddObject(newObject);
context.SaveChanges();
int id = newObject.Id; // Will give u the autoincremented ID
}
链接地址: http://www.djcxy.com/p/33552.html