首先在代码中INSERT语句与FOREIGN KEY约束冲突 [英] In Code first The INSERT statement conflicted with the FOREIGN KEY constraint
问题描述
我刚刚开始使用代码优先方法创建数据库。我有以下3个表:
I just started using Code first approach for creating databases. I have following 3 tables :
public partial class AccountHolder
{
public int AccountHolderId { get; set; }
public virtual List<Address> Address { get; set; }
}
public partial class Nominee
{
public int NomineeId { get; set; }
public virtual List<Address> Address { get; set; }
}
public partial class Address
{
public int AddressId { get; set; }
public int AccountHolderId { get; set; }
public AccountHolder AccountHolder { get; set; }
public int NomineeId { get; set; }
public Nominee Nominee { get; set; }
}
此处 AccountHolder
和被提名人
都具有与地址的 1到*
信誉。我为此使用的流畅的API代码是:
Here AccountHolder
and Nominee
both have 1 to *
replationship with the address. The fluent API code which i used for this is :
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>().HasRequired(p => p.AccountHolder)
.WithMany(p => p.Address)
.HasForeignKey(p => p.AccountHolderId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Address>().HasRequired(p => p.Nominee)
.WithMany(p => p.Address)
.HasForeignKey(p => p.NomineeId)
.WillCascadeOnDelete(false);
}
现在,我的问题是每当我尝试在AccountHolder或Nominee中插入数据时出现了此异常:
Now my issue is whenever i am trying to insert data in AccountHolder or Nominee i got this exception :
如果插入了AccountHolder
{ INSERT语句与FOREIGN KEY约束\ FK_dbo.Addresses_dbo.Nominees_NomineeId\发生冲突。冲突发生在数据库\ CodeFirst.BankContext\的表\ dbo.Nominees\中,'NomineeId'列。\r\n该语句已终止。}
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Addresses_dbo.Nominees_NomineeId\". The conflict occurred in database \"CodeFirst.BankContext\", table \"dbo.Nominees\", column 'NomineeId'.\r\nThe statement has been terminated."}
如果是被提名人插入
{ INSERT语句与FOREIGN KEY约束constraint FK_dbo.Addresses_dbo.AccountHolders_AccountHolderId\发生冲突。数据库\ CodeFirst.BankContext\的表\ dbo.AccountHolders\的 AccountHolderId列中发生冲突。\r\n该语句已终止。}
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Addresses_dbo.AccountHolders_AccountHolderId\". The conflict occurred in database \"CodeFirst.BankContext\", table \"dbo.AccountHolders\", column 'AccountHolderId'.\r\nThe statement has been terminated."}
有人可以告诉我如何解决这个问题以及我在这里缺少什么?
Cananybody please tell me how to solve this issue and what i am missing here ?
推荐答案
您尝试插入Nominees中不存在的Address Nominees_NomineeId。然后,被提名者填充值并创建Address,然后填充值最后创建AccountHolder实例。然后保存
You try to insert Address Nominees_NomineeId that is not exists in Nominee.You should First instance of Nominee then fill value and create Address and fill value last create instance of AccountHolder.and then save
这篇关于首先在代码中INSERT语句与FOREIGN KEY约束冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!