One to zero-or-one with HasForeignKey

前端 未结 2 777
不知归路
不知归路 2020-12-13 06:48

I have two models:

public class Person
{
    public virtual int Id { get; set; }
    public virtual Employee Employee { get; set; } // optional
}

public cla         


        
2条回答
  •  旧巷少年郎
    2020-12-13 07:10

    OK, I figured that out - you should use WithMany (yep, not obvious) in order to store foreign key in some property:

    Property(e => e.PersonId).HasColumnName("person_id");
    HasRequired(e => e.Person)
        .WithMany()
        .HasForeignKey(p => p.PersonId);
    

    See One-to-One Foreign Key Associations article for details. BTW this will create employee foreign key column for person's table, but there is no other way to have navigation property and foreign key separately.


    If you need foreign key read-only, you can change PersonId property to:

    public int PersonId { get { return Person.Id; } }
    

    And use your original mapping

    HasRequired(e => e.Person)
        .WithOptional(p => p.Employee)
        .Map(m => m.MapKey("person_id"));
    

提交回复
热议问题