您在Entity Framework 5.0和User实体上看到我的模型结构保持对Address和Address1实体的引用。另一方面,Address hold Users集合作为参考但是Entity框架无法知道用户依赖哪个Address引用所以我得到了异常。
它有什么解决方案?我的意思是流利且不流利的解决方案。
public class User
{
public int Id { get; set; }
public Address Address { get; set; }
public Address Address1 { get; set; }
}
public class Address
{
public int Id { get; set; }
public ICollection<User> Users { get; set; }
}
答案 0 :(得分:1)
第一步是在User class中包含外键:
public class User
{
public int Id { get; set; }
public int AddressId { get; set; }
public int Address1Id { get; set; }
public Address Address { get; set; }
public Address Address1 { get; set; }
}
Fluent API映射:
modelBuilder.Entity<User>()
.HasRequired(a => a.Address)
.WithMany()
.HasForeignKey(u => u.AddressId);
modelBuilder.Entity<User>()
.HasRequired(a => a.Address1)
.WithMany()
.HasForeignKey(u => u.Address1Id);
此处有更多详情: