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

c# entity entity-framework

Question

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.
1
11
9/5/2012 11:08:28 AM

Popular Answer

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;
17
9/5/2012 11:21:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow