【问题标题】:EF Core - Cannot insert explicit value for identity column SqlExceptionEF Core - 无法为标识列 SqlException 插入显式值
【发布时间】:2019-05-28 23:15:08
【问题描述】:

在我的应用程序中,我使用 EF Core 定义 2 个实体(代码优先),MeetingPostcodeDetail,定义如下:

public class Meeting
{
  public int Id { get; set;}
  public PostcodeDetail PostcodeDetail { get; set; }

  // other properties removed for brevity
}

public class PostcodeDetail
{
  public int Id { get; set; }
  public ICollection<Meeting> Meetings { get; set; } = new List<Meeting>();

  // other properties removed for brevity
}

当我创建一个新的Meeting 并尝试分配一个现有的PostcodeDetail 实体时,如下所示:

var meeting = new Meeting();
var details = context.PostcodeDetails
                        .SingleOrDefault(i => i.Prefix == prefix);

meeting.PostcodeDetail = details;
context.SaveChanges();

我得到了这个例外:

Microsoft.EntityFrameworkCore.DbUpdateException:SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“PostcodeDetail”中插入标识列的显式值

我不明白为什么在 PostcodeDetail 上执行插入语句,因为我正在从数据库中检索现有实体 - 谁能看到我在这里做错了什么?

编辑:当我运行 SQL Server Profiler 时,我可以看到以下内容已执行

INSERT INTO [PostcodeDetail]([Id]、[DateCreated]、[DateModified]、[District]、[Prefix]、[Region]) 值(@p0、@p1、@p2、@p3、@p4、@p5); ',N'@p0 int,@p1 datetime2(7),@p2 datetime2(7),@p3 nvarchar(4000),@p4 nvarchar(4000),@p5 nvarchar(4000)',@p0=113,@ p1='2019-01-02 15:50:49.5874691',@p2='2019-01-02 15:50:49.5874640',@p3=N'Guernsey',@p4=N'GY',@p5= N'海峡群岛'

我不知道为什么会生成插入,因为我从数据库中获取 PostcodeDetail 并在新的 Meeting 上引用它

【问题讨论】:

  • 问题可能是因为您正在尝试“创建一个新会议”,它在数据库中尚不存在,因此缺少用作主键的 ID?编辑:问题是,由于 identity_insert 已关闭,我相信您必须自己配置主键值。
  • 这里的东西可能对你有用:stackoverflow.com/questions/4682504/…
  • 这里似乎有点可疑。您是否尝试过将会议添加到 postCodeDetail.Meetings 并保存这些更改?
  • 是否有任何演示可以重现您的问题?对于您当前的代码,您没有在context.SaveChanges(); 之前调用context.Add(meeting);,它不应该对数据库进行任何更改。但是对于您的 SQL 结果,您似乎正在运行插入操作。与我们分享此操作的完整代码。
  • @Vinyl Warmth,你的问题是解决了还是仍然存在!

标签: asp.net-core entity-framework-core


【解决方案1】:

此问题的原因是我在与创建实体的上下文不同的上下文中调用 SaveChanges

【讨论】:

    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2020-02-03
    • 2015-10-27
    • 2018-06-29
    • 2021-07-02
    相关资源
    最近更新 更多