Im having two models:
public class Customer
{
public int Id { get; set; }
public int Number { get; set; }
public int ParentNumber { get; set; }
p
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.