简体   繁体   English

为什么实体框架显示该项目已被跟踪,尽管它没有被跟踪?

[英]Why does Entity Framework show that item is already tracked, despite of fact that it is not tracked?

I have 3 tests, and between every test, a new DbContext is created.我有 3 个测试,在每个测试之间,都会创建一个新的DbContext I checked it simply run 3 test cases, all added the same object to db and there was no error.我检查了它只是运行了 3 个测试用例,都将相同的 object 添加到 db 并且没有错误。 But when I run this tests:但是当我运行这个测试时:

[TestCase("test2@test.com", "test2@test.com", "123", "321", UserSaveResultStatus.UserAlreadyExists, Description = "Duplicated emails")]
[TestCase("test3@test.com", "test4@test.com", "456", "456", UserSaveResultStatus.UserWithGivenEmployeeIdAlreadyExists, Description = "Duplicated Employee Ids")]
[TestCase("test5@test.com", "test6@test.com", "", "", UserSaveResultStatus.Success, Description = "Empty Employee Ids. Should add two users")]
public void ImportUsers_Should_Add_User_Only_Once_When_Email_Or_EmployeeId_Doubled_On_The_List(string email1, string email2, string employeeId1, string employeeId2, UserSaveResultStatus expectedStatus)
{
    var emails = new string[] { email1, email2 };
    var employeeIds = new string[] { employeeId1, employeeId2 };

    var dto = GetUserImportDto(emails, employeeIds);

    var checker = dbContext.ChangeTracker
                           .Entries()
                           .Where(t => t.State == EntityState.Detached 
                                       || t.State == EntityState.Unchanged 
                                       || t.State == EntityState.Modified
                                       || t.State == EntityState.Detached
                                       || t.State == EntityState.Deleted
                                       || t.State == EntityState.Added);
    .
    .
    .
    Asserts

I get this error:我收到此错误:

The instance of entity type 'PowerPlantUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.无法跟踪实体类型“PowerPlantUser”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例。 When attaching existing entities, ensure that only one entity instance with a given key value is attached.附加现有实体时,请确保仅附加一个具有给定键值的实体实例。 Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值

I create breakpoint in place when error is thrown:抛出错误时,我在适当的位置创建断点:

foreach (var powerPlantId in newPowerPlantsIds)
{
    var personToAdd = new PowerPlantUser() { UserId = userId, PowerPlantId = powerPlantId };
    var state1 = commandsContext.Entry(personToAdd).State;
    var state2 = commandsContext.Entry(personToAdd).State; //STATE BEFORE ERROR IS DETACHED

    commandsContext.PowerPlantUsers.Add(personToAdd); //HERE IS AN ERROR

As we can see above also in test I create checker which shows me tracked entries.正如我们在上面的测试中看到的那样,我创建了检查器,它显示了跟踪的条目。 New PowerPlantUser has id = 0 and there is no this user in checker.新 PowerPlantUser 的 id = 0 并且检查器中没有此用户。

When I run tests separately, there is no error and all tests passed.当我单独运行测试时,没有错误并且所有测试都通过了。 Can someone tell me where the problem is?谁能告诉我问题出在哪里?

The error implies that a different instance of a PowerPlantUser with that same ID is already tracked by the DbContext.该错误意味着 DbContext 已跟踪具有相同 ID 的 PowerPlantUser 的不同实例 It is also referring to an "Id" column so while you are providing a UserId and PowerPlantId I'd check to see if you are implementing some base class or such defining a common "Id" column that isn't being set up correctly as an Identity resulting in each record possibly going into the DB with a PK of "0".它还指的是“Id”列,因此当您提供 UserId 和 PowerPlantId 时,我会检查您是否正在实现一些基本 class 或定义一个未正确设置的常见“Id”列一个标识,导致每条记录可能以“0”的 PK 进入数据库。

  1. Check your PowerPlantUser definition for an Id column and whether it is correctly set up as an Identity column.检查您的 PowerPlantUser 定义的 Id 列以及它是否正确设置为 Identity 列。 (Can also depend on which Database you are using for testing.) (也可以取决于您用于测试的数据库。)

  2. Check the local tracking cache for a matching entity.检查本地跟踪缓存以查找匹配实体。 If the PK is definitely the PowerPlantId + UserId, then add the following code to confirm if the Context is tracking an existing entity:如果 PK 肯定是 PowerPlantId + UserId,则添加以下代码以确认 Context 是否正在跟踪现有实体:

.. ..

var existingItem = commandsContext.PowerPlantUsers.Local
    .SingleOrDefault(x => x.PowerPlantId == powerPlantId && x.UserId == userId);

That checks the tracking cache for the DbContext.这会检查 DbContext 的跟踪缓存。 If that returns an entity then something else is inserting and leaving a tracked instance in the DbContext.如果它返回一个实体,那么其他东西会在 DbContext 中插入和留下一个跟踪的实例。

暂无
暂无

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

相关问题 DbContext 抛出已经跟踪的实体,但没有跟踪实体 - DbContext throw already tracked entity but no entity tracked 实体框架核心 - 无法跟踪实体类型的实例,因为已在跟踪具有键值的另一个实例 - Entity framework Core - The instance of entity type cannot be tracked because another instance with the key value is already being tracked 无法跟踪实体类型“Item”的实例,因为已跟踪另一个具有与 {'Id'} 相同键值的实例 - The instance of entity type 'Item' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 异常实体已被跟踪 - Exception Entity Is Already Being Tracked 如何为实体框架已经跟踪的记录加载相关数据 - How to load related data for a record already being tracked by Entity Framework 实体框架参考 - 无法跟踪 - Entity Framework reference - cannot be tracked 实体框架核心 - 无法跟踪实体类型的实例,因为已在跟踪具有相同键的此类型的另一个实例 - Entity Framework core - The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked 实体类型的实体框架实例无法跟踪 - Entity Framework instance of entity type cannot be tracked 实体框架未跟踪更新实体 - Update Entity Not Being Tracked By Entity Framework 检查实体框架上下文是否正在跟踪实体 - Check if entity is being tracked by Entity Framework context
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM