我需要创建一个关系,我有一个链接到地址表的用户表。问题是我需要地址表来存储历史地址。用户可能根本没有地址。
public class user
{
public virtual int ID { get; set; }
...
public virtual int? AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<Address> HistoricAddresses { get; set; }
}
public class Address
{
public virtual int ID { get; set; }
...
}
我尝试了各种方法来使其工作并遇到各种错误,例如在用户和地址之间放置另一个表:
public class HistoricAddress
{
public virtual int ID { get; set; }
public Address HistoricAddress { get; set; }
}
public class user
{
public virtual int ID { get; set; }
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<HistricAddress> HistoricAddresses { get; set; }
...
}
以及其他各种方式,但这也会引发错误。必须有一个正确的方法来做到这一点。我得到的最后一个错误是:
“System.Data.Entity.Infrastructure.DbUpdateException:更新条目时发生错误。有关详细信息,请参阅内部异常.---&gt; System.Data.UpdateException:更新条目时发生错误。请参阅详细内部异常.---&gt; System.InvalidOperationException:ReferentialConstraint中的依赖属性映射到存储生成的列。列:'ID'。“
答案 0 :(得分:4)
您可以使用3个表格映射以下模型。
public class user
{
public virtual int ID { get; set; }
...
public virtual int? AddressId { get; set; }
public virtual Address CurrentAddress { get; set; }
public virtual ICollection<Address> HistoricAddresses { get; set; }
}
public class Address
{
public virtual int ID { get; set; }
public virtual ICollection<User> Users { get; set; }
...
}
覆盖自定义OnModelCreating
DbContext
方法
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(user => user.CurrentAddress).WithMany()
.HasForeignKey(user => user.AddressId);
modelBuilder.Entity<User>()
.HasMany(user => user.HistoricAddresses)
.WithMany(address => address.Users)
.Map(m =>
{
m.ToTable("UserAddresses");
m.MapLeftKey("UserId");
m.MapRightKey("AddressId");
});
}
创建的表格是