AspNet EF referencing foreign key to field

狂风中的少年 提交于 2019-12-02 02:39: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<Customer>()
    .HasAlternateKey(e => e.Number);

Then set up the relationship as follows:

modelBuilder.Entity<Batch>()
    .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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!