多对多自参考

一个用户可以管理多个公司。并且用户可以从多公司列表中一次拥有一个活跃的公司。我怎么能做到这一点?


我目前的模型是:


public class User

{

    public int Id


    public virtual ICollection<Company> Companies { get; set; }


    public User()

    {

        this.Companies = new HashSet<Company>();

    }

}

public class Company

{

    public int Id


    public virtual ICollection<User> Users { get; set; }


    public User()

    {

        this.Users = new HashSet<User>();

    }

}

如果我添加另一个注释:


public class User

{

    public int CompanyId


    public virtual Company Company { get; set; }

}

该模型不会引用多对多表哪个UserCompany表。


我怎么能做到这一点?或者这种情况有另一种方法吗?

http://img3.mukewang.com/61a337a80001359208500209.jpg

现在我正在考虑制作手动多对多关系模型并添加ActiveCompany从自定义多对多关系引用的另一个字段。这是好方法吗?


慕的地10843
浏览 175回答 2
2回答

largeQ

我很确定你可以通过使用 fluent api 并覆盖OnModelCreating你的 中的方法来做到这一点DbContext,但我没有手头的例子。但是,您可能会发现为您的用户添加另一个属性更容易public int ActiveCompanyId { get; set; }有很多变量,例如您是否使用延迟加载、有多少公司/用户、您的数据访问模式是什么,这可能决定您的最佳整体方法。如果您的Companies属性通常或总是被填充,那么您可以创建一个get未映射的唯一属性:public class User{&nbsp; &nbsp; public int Id&nbsp; &nbsp; public virtual ICollection<Company> Companies { get; set; }&nbsp; &nbsp; public int ActiveCompanyId { get; set; }&nbsp; &nbsp; [NotMapped]&nbsp; &nbsp; public Company ActiveCompany&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this.Companys == null ? null :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Companies.Where(x => x.Id == this.Active.CompanyId)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.SingleOrDefault;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public User()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;this.Companies = new HashSet<Company>();&nbsp; &nbsp; }}

撒科打诨

你能试试这个映射吗:protected override void OnModelCreating(DbModelBuilder modelBuilder){&nbsp; &nbsp; modelBuilder.Entity<Company>()&nbsp; &nbsp; &nbsp; &nbsp; .HasMany(c => c.Users)&nbsp; &nbsp; &nbsp; &nbsp; .WithMany(u => u.Comapnies)&nbsp; &nbsp; &nbsp; &nbsp; .Map(x =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.MapLeftKey("CompanyId");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.MapRightKey("UserId");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.ToTable("UserCompany");&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; modelBuilder.Entity<User>()&nbsp; &nbsp; &nbsp; &nbsp; .HasRequired(b => b.Company)&nbsp; &nbsp; &nbsp; &nbsp; .WithMany()&nbsp; &nbsp; &nbsp; &nbsp; .WillCascadeOnDelete(false);}
打开App,查看更多内容
随时随地看视频慕课网APP