问题描述
在我的应用程序中,我使用EF Core定义2个实体(代码优先"), Meeting
和 PostcodeDetail
定义如下:
公开课会议{public int ID {get;放;}公共PostcodeDetail PostcodeDetail {get;放;}//为简洁起见,删除了其他属性}公共类PostcodeDetail{public int ID {get;放;}公共ICollection< Meeting>会议{放;} = new List< Meeting>();//为简洁起见,删除了其他属性}
当我创建一个新的 Meeting
并尝试分配一个现有的 PostcodeDetail
实体时,如下所示:
var Meeting = new Meeting();var details = context.PostcodeDetails.SingleOrDefault(i => i.Prefix ==前缀);Meeting.PostcodeDetail =详细信息;context.SaveChanges();
我收到此异常:
当我从数据库中检索现有实体时,我看不到为什么在 PostcodeDetail
上执行insert语句-有人能看到我在做什么错吗?
:当我运行SQL Server Profiler时,可以看到以下内容已执行
我不知道为什么会生成插入,因为我是从数据库中获取PostcodeDetail并在新的 Meeting
此问题的原因是我在与创建实体所使用的上下文不同的上下文中调用了 SaveChanges
./p>
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:
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
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
The cause of this issue was that I was calling SaveChanges
on a different context to the context I was creating the entity with.
这篇关于EF Core-无法为身份列SqlException插入显式值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!