Im having two models:
public class Customer
{
public int Id { get; set; }
public int Number { get; set; }
public int ParentNumber { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Language { get; set; }
}
and
public class Batch
{
public int Id { get; set; }
public int Number { get; set; }
public string FileName { get; set; }
public string ArticleNumber { get; set; }
public string ArticleDescription { get; set; }
public int Weight { get; set; }
public DateTime ProductionDate { get; set; }
public DateTime DeliveryDate { get; set; }
public DateTime BestBeforeDate { get; set; }
public DateTime? ApprovedDateTime { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
One batch can have a customer attached to it. But since we're importing the data from another system we decided not to take over their id's
.
Right now the foreign key says try to find a customer by the property Customer.Id
I'm trying to achieve to get the foreign key point to Customer.Number
from Batch.Customer(Id)
How would i succeed in this? I've tried by defining the Customer.Number to be a Key with the Key attribute.. but this made the primary key go from Id to Number which is not what i wanted...
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:Then set up the relationship as follows:
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.