Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 440
Jan Matousek Avatar asked Sep 05 '12 11:09

Jan Matousek


1 Answers

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;
  }
like image 73
ElConrado Avatar answered Oct 08 '22 10:10

ElConrado