Entity Framewok 正在尝试为多对多关系插入集合值

问题描述 投票:0回答:0

我有一个关于此问题的简单示例 - 它工作正常(在我的单元测试中)。但是我看不出我在复杂情况下的代码有什么不同。并且 EF 确实为这种关系创建了预期的连接表。这是设置:

public class User
    {
    public int Id { get; private set; }
    public ICollection<Interest> Interests { get; set; }
    }

public class Interest
    {
    public int Id { get; private set; }
    public ICollection<User> Users { get; set; }
    }

// ...

public void NewUser(MyDbContext context, Interest interest) {
    User user = new User();
    user.Interests.Add(interest);
    context.Users.Add(user);
    _ = await context.SaveChangesAsync();
    }

这会抛出以下内容:

Microsoft.EntityFrameworkCore.DbUpdateException
  HResult=0x80131500
  Message=An error occurred while saving the entity changes. See the inner exception for details.
  Source=Microsoft.EntityFrameworkCore.Relational
  StackTrace:
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__50.MoveNext()
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.<ExecuteAsync>d__17.MoveNext()
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__9.MoveNext()
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__9.MoveNext()
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__9.MoveNext()
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__106.MoveNext()
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__110.MoveNext()
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
   at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__64.MoveNext()
   at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__64.MoveNext()
   at LouisHowe.core.Data.LouisHoweDbContext.<SaveChangesAsync>d__4.MoveNext() in C:\git\LouisHowe\LouisHowe.core\Data\LouisHoweDbContext.cs:line 45
   at LouisHowe.web.Pages.Account.Register.<HandleValidSubmitAsync>d__71.MoveNext() in C:\git\LouisHowe\LouisHowe.web\Pages\Account\Register.razor.cs:line 240

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
SqlException: CCannot insert explicit value for identity column in table 'Interests' when IDENTITY_INSERT is set to OFF.

需要注意的一点是,之前使用只读 DbContext 读取了 Interest 对象。来自相同的数据库但不同的 DbContext 并且该 DbContext 现在超出范围。

这会是问题所在吗?问题是不同的 DbContext 和/或感兴趣的 DbContext 现在超出范围了吗?

entity-framework entity-framework-core
© www.soinside.com 2019 - 2024. All rights reserved.