[英]How can I reference multiple foreign key in one table to a single primary key in ms sql
[英]Can I reference single foreign key on multiple columns in a table? If yes, how to configure it in Entity Framework core
如何使用 Entity Framework 核心生成类似结构的上表?
我正在使用代码优先方法从域模型生成我的表,如下所示
public class Contact
{
public int ContactId { get; set; }
public string Email { get; set; }
public string Name { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
[ForeignKey("Contact")]
public int FirstContact { get; set; }
[ForeignKey("Contact")]
public int SecondContact { get; set; }
[ForeignKey("Contact")]
public int ThirdContact { get; set; }
public virtual Contact Contact { get; set; }
}
在公司表中,我希望列 'FirstContact'、'SecondContact'、'ThirdContact' 上的外键可以引用联系人表。
我也尝试过 Fluent API 但也没有成功。
每当我运行 add-migration 命令时,都会收到此错误:
[ForeignKey] 属性指向导航“Company.Contact”的多个属性。 要使用数据注释定义复合外键,请使用导航上的 [ForeignKey] 属性。
我将不胜感激有关相同的任何帮助。
谢谢。
对于多个导航属性,您需要多个外键。 例如
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public virtual Contact FirstContact { get; set; }
public virtual Contact SecondContact { get; set; }
public virtual Contact ThirdContact { get; set; }
}
让 EF Core 为您的 FK 或使用外键属性创建影子属性:
public class Company
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int FirstCotactId {get; set;}
public virtual Contact FirstContact { get; set; }
public int SecondCotactId {get; set;}
public virtual Contact SecondContact { get; set; }
public int SecondCotactId {get; set;}
public virtual Contact ThirdContact { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.