I have two classes that are linked by the foreign key “PickingListId”. They are both drawing data from SQL Views, so I’ve renamed my PickingList to PickingListView. It worked fine before as it seemed to be guessing the Foreign Key correctly (PickingListId). However now it’s trying to guess that the Foreign key is “PickingListViewId” so I’ve tried to explicitly mark the foreign key.
Below are my two classes. I’ve had [Key] and [ForeignKey] annotations which I’ve removed, believing that they might be clashing with Fluent API.
public class PickingListView
{
public int PickingListId { get; set; }
public ICollection<PickingListLine> Lines { get; set; }
}
public class PickingListLine
{
public int PickingListLineId { get; set; }
public int PickingListId { get; set; }
public PickingListView PickingListView { get; set; }
}
Below is my Fluent API configuration:
modelBuilder.Entity<PickingListView>(entity =>
{
entity.ToView("view_PickingList").HasKey(e => e.PickingListId);
entity.HasMany(e => e.Lines)
.WithOne(e => e.PickingListView)
.HasForeignKey(e => e.PickingListId)
.IsRequired();
});
modelBuilder.Entity<PickingListLine>(entity =>
{
entity.ToView("view_PickingListLine").HasKey(e => e.PickingListLineId);
entity.Property(e => e.PickingListId).HasColumnName("PickingListId");
entity.HasOne(e => e.PickingListView)
.WithMany(e => e.Lines)
.HasForeignKey(e => e.PickingListId);
});
Since adding the the configuration to PickingListLine in Fluent API I am now receiving the error
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name ‘PickingListId1’.
I’ve had a look at the generated SQL and the joins are correctly using PickingListId, however it’s trying to select a PickingListId1 column, which does not exist.
How do I correctly mark the PickingListLine’s PickingListId as the foreign key to link to the PickingListView class?