AspNet EF referencing foreign key to field

前端 未结 1 690
情歌与酒
情歌与酒 2021-01-23 02:04

Im having two models:

public class Customer
{
    public int Id { get; set; }
    public int Number { get; set; }
    public int ParentNumber { get; set; }
    p         


        
1条回答
  •  情歌与酒
    2021-01-23 02:18

    What are you asking was impossible in EF prior to EF Core. Fortunately in EF Core it can be done by using Alternate Keys feature. But please note that in order to be able to use it, your Cusomer.Number field should be unique.

    The solution requires Fluent API configuration.

    Start by defining Customer.Number as alternate key:

    modelBuilder.Entity()
        .HasAlternateKey(e => e.Number);
    

    Then set up the relationship as follows:

    modelBuilder.Entity()
        .HasOne(e => e.Customer)
        .WithMany()
        .HasForeignKey(e => e.CustomerId)
        .HasPrincipalKey(e => e.Number);
    

    The last two lines will do what you are seeking for.

    As a side note, it would be better to name the property (and column) CustomerNumber in order to avoid confusion of what the value is in it.

    0 讨论(0)
提交回复
热议问题