How can I get Id of inserted entity without saveChanges in Entity framework?
This question already has an answer here:
//MyClass has Id as property, this is set by the DB server
var myObject = new MyClass { NotIdProp = someVal; }
int idAfterInsert; //or string if using GUID for Id
//transaction and then dispose DB context
using (var db = new MyContext())
{
//add the entity object
db.MyTable.Add(myObject);
//now myObject will have its Id set by the DB server
idAfterInsert = myObject.Id;
//that's it if you don't want to Save Changes
}
However, I don't see a pattern where this can be useful, if your object should be pending instead of saved at this stage just add another SQL column, something like Submitted or Approved and make it a bit
value (boolean in C#).
Then when reading records, don't fetch ones which you don't want to by filtering on the bool column.
If you use a Sequence to generate your key values instead of an IDENTITY column, you can fetch the key value before inserting into the database.
EF Core supports this natively Sequences, and you can do this in EF6 with a little custom SQL.
链接地址: http://www.djcxy.com/p/33554.html上一篇: 用于组合数据的实体框架算法