【问题标题】:How to add two foreign keys in the same class (table) in EF如何在EF的同一个类(表)中添加两个外键
【发布时间】:2023-03-07 12:15:02
【问题描述】:

我正在使用 EF 项目,我尝试添加两个外键,但在添加迁移时遇到了问题。

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public DateTime? DeathDate { get; set; }

    public int? FatherId { get; set; }
    public int? MotherId { get; set; }

    [ForeignKey("FatherId")]
    public virtual Person Father { get; set; }

    [ForeignKey("MotherId")]
    public virtual Person Mother { get; set; }
}

【问题讨论】:

  • 是的,我收到一个错误:
  • 错误:无法确定“Person”类型的导航“Person.Mother”所代表的关系。手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性。
  • edit您的问题添加新信息。您是否尝试过异常告诉您的内容? IE。 “手动配置关系”。你至少应该对这样的消息做点什么,它的存在是有原因的。
  • 另外,请使用显示您正在使用的 EF 版本的标签。

标签: c# entity-framework


【解决方案1】:

在您的上下文中添加此代码

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>()
        .HasOptional(a => a.Mother)
        .WithMany()
        .HasForeignKey(a => a.MotherId);

    modelBuilder.Entity<Person>()
        .HasOptional(a => a.Father)
        .WithMany()
        .HasForeignKey(a => a.FatherId);
}

        ```

【讨论】:

  • 谢谢@RositaEsmaili,您的回答有效。
猜你喜欢
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
相关资源
最近更新 更多