【发布时间】:2014-08-08 19:46:23
【问题描述】:
我想要如下表结构:
Person
-person_id
Company
-company_id
Company_Person
-person_id
-company_id
-other_column
Location
-id
目前我的 EF 导致 Person 表中的“company_id”列也作为 FK。
我的模型看起来像:
public class Person
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
public int LocationId {get;set;}
public virtual Location Location {get; set; }
public virtual ICollection<CompanyPerson> CompanyPersons {get; set;}
}
public class Company
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CompanyId { get; set; }
public virtual ICollection<CompanyPerson> CompanyPersons {get; set;}
}
[Table("Company_Person")]
public class CompanyPerson
{
[Key, Column(Order = 0)]
public int PersonId { get; set; }
[Key, Column(Order = 1)]
public int CompanyId { get; set; }
public bool IsActive { get; set; }
public virtual Person Person { get; set; }
public virtual Company Company { get; set; }
}
public class Location
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id {get;set;}
public virtual ICollection<Person> Persons {get;set;}
}
我遵循与此处相同的模式:Create code first, many to many, with additional fields in association table
如何在 Person 表中生成额外的 CompanyId 列?
更新
好吧,我想通了,事实证明这是我没有发布的另一个关联(我又一次错了)。
在我的公司模型中,我将其注释掉并生成了正确的表格。我仍然想要这个关联,所以有人可以告诉我这是什么原因吗?
public class Company
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CompanyId { get; set; }
public virtual ICollection<CompanyPerson> CompanyPersons {get; set;}
public virtual ICollection<History> Histories {get; set; }
}
public class History
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Company")]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
因此,当我注释掉 History 模型中除 Id 属性和 Company.History 属性之外的所有内容时,它生成了我期望的表结构。
【问题讨论】:
-
不是也给Company添加了PersonID?
-
一秒钟我要进行编辑,忘记了 1 个模型
-
@Pheonixblade9 我用另一个模型更新了我的问题,以防对 EF 造成一些“混乱”。
-
这更没有意义。这个
History类和Person之间甚至没有关系。继续挖掘。肯定有更多,因为您仍然没有任何代码会导致这种情况。 -
也许这是 EF 6.1 中的一个错误?我可以在 OnModelCreating 事件中添加一些内容以使其更加明确吗?
标签: c# asp.net-mvc entity-framework entity-framework-6.1