Home > Net >  How to add two foreign keys in the same class (table) in EF
How to add two foreign keys in the same class (table) in EF

Time:12-18

I'm working with EF project and I try to add two foreign keys but I have a problem when I do Add Migration.

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; }
}

CodePudding user response:

Add This code in your context

   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);
}

        ```
  • Related