Entity Framework - retrieve ID before 'SaveChanges' inside a transaction

前端 未结 5 1269
盖世英雄少女心
盖世英雄少女心 2020-11-29 06:12

In Entity Framework - Is there any way to retrieve a newly created ID (identity) inside a transaction before calling \'SaveChanges\'?

I need the ID for a second inse

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 06:48

    As others have already pointed out, you have no access to the increment value generated by the database before saveChanges() was called – however, if you are only interested in the id as a means to make a connection to another entity (e.g. in the same transaction) then you can also rely on temporary ids assigned by EF Core:

    Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges().

    Here is an example to demonstrate how this works. Say MyEntity is referenced by MyOtherEntity via property MyEntityId which needs to be assigned before saveChanges is called.

    var x = new MyEntity();        // x.Id = 0
    dbContext.Add(x);              // x.Id = -2147482624 <-- EF Core generated id
    var y = new MyOtherEntity();   // y.Id = 0
    dbContext.Add(y);              // y.Id = -2147482623 <-- EF Core generated id
    y.MyEntityId = x.Id;           // y.MyEntityId = -2147482624
    dbContext.SaveChangesAsync();
    Debug.WriteLine(x.Id);         // 1261 <- EF Core replaced temp id with "real" id
    Debug.WriteLine(y.MyEntityId); // 1261 <- reference also adjusted by EF Core
    

    The above also works when assigning references via navigational properties, i.e. y.MyEntity = x instead of y.MyEntityId = x.Id

提交回复
热议问题