这是场景一,效果很好:
public class Domain
{
public int DomainId { get; set; }
[InverseProperty("Domain")]
public virtual ICollection<Person> Persons { get; set; }
[InverseProperty("Domain")]
public virtual ICollection<Group> Groups { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public virtual Domain Domain { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
public class Group
{
public int GroupId { get; set; }
public virtual Domain Domain { get; set; }
public virtual ICollection<Person> Members { get; set; }
}
这是场景二,它失败了。
public class Domain
{
// Same as scenario 1...
}
public class Person
{
public int PersonId { get; set; }
public int DomainId { get; set; } // <--- new
[ForeignKey("DomainId")] // <--- new
public virtual Domain Domain { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
public class Group
{
public int GroupId { get; set; }
public int DomainId { get; set; } // <--- new
[ForeignKey("DomainId")] // <--- new
public virtual Domain Domain { get; set; }
public virtual ICollection<Person> Members { get; set; }
}
方案 2 中的错误消息如下: 引用关系将导致不允许的循环引用。[约束名称 = FK_dbo.GroupMembers_dbo.Persons_MemberId]
这两种情况都有这个映射(多对多),在 OnModelCreating 的方法中。
modelBuilder.Entity<Group>()
.HasMany(group => group.Members)
.WithMany(member => member.Groups)
.Map(m =>
{
m.ToTable("GroupMembers");
m.MapLeftKey("GroupId");
m.MapRightKey("MemberId");
});
我究竟做错了什么?!我想要达到的目的是完全合理的