我刚刚提出问题并得到了解决方案,但解决方案产生了一个我在这里提到的新问题。AccountHolder
在这里,我修改了我的代码并在和之间创建了一个新的 1 对 1 关系Nominee
。
public partial class AccountHolder
{
public int AccountHolderId { get; set; }
public virtual List<Address> Address { get; set; }
public virtual Nominee Nominee { 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; }
}
它们之间的关系如下:
1 to many between AccountHolder and Address
1 to many between Nominee and Address
1 to 1 between AccountHolder and Nominee
流利的 Api 代码是:
modelBuilder.Entity<AccountHolder>().HasOptional(p => p.Nominee)
.WithRequired()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Address>().HasRequired(p => p.AccountHolder)
.WithMany(p => p.Address)
.HasForeignKey(p => p.AccountHolderId)
.WillCascadeOnDelete();
modelBuilder.Entity<Address>().HasRequired(p => p.Nominee)
.WithMany(p => p.Address)
.HasForeignKey(p => p.NomineeId)
.WillCascadeOnDelete();
首先,如果有任何改进的范围,请建议我。现在我在这里面临的问题是每当我插入时AccountHolder
我必须创建一个空实例,Nominee
而在插入时Nominee
我必须创建一个空实例AccountHolder
。如果我不这样做,就会发生我在上一个问题中提到的错误。任何人都可以指导我如何解决这个问题,请在您的解决方案中添加示例代码。
我用于插入数据的代码是:
var accountHolder = new AccountHolder() {
AccountHolderId = 901,
Address = new List<Address>()
{
new Address()
{
HouseNumber = hnumber,
Street = street,
Nominee = new Nominee() //this is the issue
}
},
Nominee = new Nominee()
{
Address = new List<Address>()
{
new Address()
{
HouseNumber = n_hnumber,
Street = n_street,
AccountHolder = new AccountHolder() //this is the issue
}
}
}
};
谢谢!