【问题标题】:Table-Per-Type and multiple association using same Foreign Key in Entity Framework CodeFirstTable-Per-Type 和在实体框架代码优先中使用相同外键的多重关联
【发布时间】:2014-03-07 05:23:36
【问题描述】:

我有以下 CodeFirst 类。我正在尝试在这里建模 TPT 结构。用户可以登录并访问他的个人资料或他的许多公司资料。 IndividualCompany 与其他表具有多态关联。

public class LoginDetail
{
      public int Id { get; set; }
      //Other Properties

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

public abstract class Profile
{
      public int Id { get; set; }
      //Other Properties
      public virtual int LoginId { get; set; }
      public virtual LoginDetail Login{ get; set; }
}

[Table("Individuals")]
public class Individual : Profile
{
      //Other Properties
}

[Table("Companies")]
public class Company: Profile
{
      //Other Properties
}

这映射到LoginDetailsProfilesIndividualsCompanies 表。一切正常,但为了将LoginDeatilsCompanies 之间的一对多关系关联起来,它会在Companies 表中创建一个额外的LoginDetail_Id。这破坏了我模型的其他部分。我如何告诉实体框架在Profiles 表中使用LoginId 来处理LoginDeatilsIndividuals 之间的一对一关系以及LoginDeatilsCompanies 之间的一对一关系

【问题讨论】:

    标签: entity-framework ef-code-first foreign-key-relationship polymorphic-associations table-per-type


    【解决方案1】:

    你应该使用 InverseProperty 和 ForeignKey 属性,

    试试这个代码:

    public class LoginDetail
    {
      public int Id { get; set; }
      //Other Properties
    
      public virtual Individual Individual { get; set; }
    
      [InverseProperty("Login")]
      public virtual ICollection<Profile> Profiles{ get; set; }
    }
    
    
    public abstract class Profile
    {
      public int Id { get; set; }
      //Other Properties
      public virtual int LoginId { get; set; }
    
      [InverseProperty("Profiles")]
      [ForeignKey("LoginId")]
      public virtual LoginDetail Login{ get; set; }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      相关资源
      最近更新 更多