EF 6 Fluent API,具有一对多和多对多以及冲突的多重性



我一直无法找到这个特定问题的答案,也许是因为我对实体框架的陌生

我有两个实体:用户和设施。

设施

表需要所有者(用户(,但设施也可以将许多"设施用户"分配给设施。

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);

问题是,当我将设施点映射到所有者时,我收到以下错误:在类型"MEH"上声明的导航属性"设施用户"。Web.Models.Entities.Facility'已经配置了相互冲突的多重性

但是,当我排除设施到所有者映射时,它可以工作。

//One to Many: Facility To Owner
//modelBuilder.Entity<Facility>()
//    .HasRequired<User>(s => s.Owner)
//    .WithMany(s => s.Facilities)
//    .HasForeignKey(k => k.OwnerId);

问题是,设施表随后有一个空的Owner_UserId字段,但所有者 ID 已正确填写。 在我解决"Owner_UserId"问题之前,我的强迫症不会让我继续前进。

谢谢D

不能

一个集合导航属性 ( 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);

相关内容

  • 没有找到相关文章

最新更新