In my database I have the two tables tblOrders
and tblPayments
, both containing a property named ReferenceNumber (varchar 50)
. Unfortunately tblPayments
doesn't have a foreign key pointing to tblOrders
, so the only way to put the records from these two tables in relationship is by referring to the matching ReferenceNumber
(1 order can have n payments).
In my ASP.NET Core 1.1 application that uses Entity Framework Core I'm trying to define this relationship for two models Order.cs
and Payment.cs
.
In the related configuration files I tried to set them up as following:
OrderConfiguration.cs:
public void Map(EntityTypeBuilder<Order> builder)
{
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).HasColumnName("ID");
... several other mappings...
builder.HasMany(m => m.Payments).WithOne(p => p.Order).HasForeignKey(m => m.ReferenceNumber);
builder.ToTable("tblOrders");
}
PaymentConfiguration.cs:
public void Map(EntityTypeBuilder<Payment> modelBuilder)
{
modelBuilder.HasKey(m => m.Id);
modelBuilder.Property(m => m.Id).HasColumnName("ID");
... several other mappings...
modelBuilder.HasOne(m => m.Order).WithMany(o => o.Payments).HasForeignKey(m => m.ReferenceNumber);
modelBuilder.ToTable("tblPayments");
}
when I debug the application, i obtain the following exception:
System.InvalidOperationException: 'The relationship from 'Payment.Order' to 'Order.Payments' with foreign key properties {'ReferenceNumber' : string} cannot target the primary key {'Id' : int} because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.'
This sounds pretty reasonable, but how can i set the relationship properly considering the situation mentioned above?