我还没有找到这个具体问题的答案,也许是因为我对实体框架的新见解
我有两个实体:用户和设施。
Facility表需要所有者(用户),但Facility也可以拥有许多" FacilityUsers"分配给工厂。
public class User
{
....
public virtual ICollection<Facility> Facilities { get; set; }
}
public Facility Facility
{
public Guid OwnerId { get; set; }
...
public virtual User Owner { get; set; }
public virtual ICollection<User> FacilityUsers { get; set; }
}
这是我的模型构建器
////Many To Many: Users To Facilities
modelBuilder.Entity<User>()
.HasMany(i => i.Facilities)
.WithMany(u => u.FacilityUsers)
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("FacilityId");
m.ToTable("UserFacility");
});
//One to Many: Facility To Owner
modelBuilder.Entity<Facility>()
.HasRequired<User>(s => s.Owner)
.WithMany(s => s.Facilities)
.HasForeignKey(k => k.OwnerId);
问题是,当我有地图设施所有者时,我收到以下错误:导航属性&#39; FacilityUsers&#39;在类型&#39; MEH.Web.Models.Entities.Facility&#39;上声明已配置了多重冲突。
但是,当我排除设施到所有者映射时,它可以正常工作。
//One to Many: Facility To Owner
//modelBuilder.Entity<Facility>()
// .HasRequired<User>(s => s.Owner)
// .WithMany(s => s.Facilities)
// .HasForeignKey(k => k.OwnerId);
问题是,设施表的 Owner_UserId 字段为空,但 OwnerId 已正确填写。我的OCD不让我继续前进,直到我解决了&#34; Owner_UserId&#34;问题
谢谢你, d
答案 0 :(得分:2)
您无法将一个集合导航属性(Facilities
)映射到两个关系。
为one-to-many
关系添加另一个集合:
public class User
{
....
public virtual ICollection<Facility> Facilities { get; set; }
public virtual ICollection<Facility> OwnedFacilities { get; set; }
}
并映射它:
//One to Many: Facility To Owner
modelBuilder.Entity<Facility>()
.HasRequired(s => s.Owner)
.WithMany(s => s.OwnedFacilities) // <- another collection
.HasForeignKey(k => k.OwnerId);
或保持User
模型不变,但将one-to-many
关系配置为单向(不带集合导航属性):
//One to Many: Facility To Owner
modelBuilder.Entity<Facility>()
.HasRequired(s => s.Owner)
.WithMany() // <- no collection
.HasForeignKey(k => k.OwnerId);