EF Core - Cannot insert explicit value for identity column SqlException

北战南征 提交于 2020-06-29 01:11:34

问题


In my app I am using EF Core to define 2 entities (Code First), Meeting and PostcodeDetail defined as follows:

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
}

When I create a new Meeting and try assigning an existing PostcodeDetail entity as follows:

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

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

I get this exception:

Microsoft.EntityFrameworkCore.DbUpdateException: SqlException: Cannot insert explicit value for identity column in the table 'PostcodeDetail' when IDENTITY_INSERT is set to OFF

I can't see why an insert statement is executing on PostcodeDetail, as I am retrieving an exisiting entity from the database - can anyone see what I'm doing wrong here?

Edit: When I run SQL Server Profiler I can see the following is executed

INSERT INTO [PostcodeDetail] ([Id], [DateCreated], [DateModified], [District], [Prefix], [Region]) VALUES (@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'Channel Islands'

I don't know why an insert is generated, as I am getting the PostcodeDetail from the database and referencing it on the new Meeting


回答1:


The cause of this issue was that I was calling SaveChanges on a different context to the context I was creating the entity with.



来源:https://stackoverflow.com/questions/54004098/ef-core-cannot-insert-explicit-value-for-identity-column-sqlexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!