简体   繁体   English

从最近插入的对象中检索ID

[英]Retrieve ID from recently inserted object

I am using EF Core with my own Unit-of-Work and generic repository pattern. 我将EF Core与我自己的工作单元和通用存储库模式一起使用。 I have a shadow property linking to entities that have no direct relationship in the db. 我有一个影子属性,链接到在数据库中没有直接关系的实体。 So I perform a UOW adding to two tables utilising the shadow property to get the ID from the first insert and placing it as a foreign key in the second without a constraint. 因此,我执行了一个UOW,利用shadow属性将其添加到两个表中,以从第一个插入中获取ID,并将其作为外键放置在第二个表中,而没有任何约束。 This all works fine and the newly inserted record in both tables correspond. 一切正常,两个表中新插入的记录都对应。 So the primary key of the first table is placed in the second successfully, so I have my shadow relationship. 因此,第一个表的主键已成功放置在第二个表中,所以我有我的影子关系。

What I can't do is access this new ID field in C# code so I can then return it to the client. 我无法执行的操作是使用C#代码访问此新ID字段,然后将其返回给客户端。

Something like this.. 像这样

      int entity1ID = _unitOfWork.entity1Repository.AddEntity1(entity1);
      //The value in entity1ID is -2147482647. This is used to map the shadow property.
      int entity2ID = _unitOfWork.entity2Repository.AddEntity2(entity2);
      int resultCount = await _unitOfWork.SaveChangesAsync();

After this process is completed the everything works. 此过程完成后,一切正常。 I cannot get hold of the entity1ID field, if I check it then it still has the value -2147482647 inside it. 我无法掌握entity1ID字段,如果我对其进行检查,则它内部仍具有值-2147482647。 Does anyone know of a decent solution to this problem. 有谁知道这个问题的解决方案。

完成SaveChangesAsync() ,您可以像这样检索shadow属性的值:

var entity1ID = dbContext.Entry(entity1).Property("ID").CurrentValue; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM