I have a SQL database (which isn't normalized and doesn't have primary keys, only indexes which I cannot change the schema of) that has a many-to-many relationship.
Reservations can have many Customers and vice-versa. The Reservation table is keyed off ReservationID and TransactionLineNumber. The Customer table has IPCode as its key.
There is a lookup table that is used to create this relationship that has the three keys and nothing else.
Below is my DbContext configuration code:
modelBuilder.Entity<ReservationDetail>()
.HasMany(rd => rd.LinkedCustomers)
.WithMany(c => c.Reservations)
.Map(m =>
{
m.ToTable("r_transaction_detail_ip");
m.MapLeftKey("reservation_id", "transaction_line_number");
m.MapRightKey("ip_number");
});
Here are snippets of the classes for each, and their entity configurations:
Customer
public class Customer
{
public string IpNumber { get; set; }
public string CustomerName { get; set; }
public virtual ICollection<ReservationDetail> Reservations { get; set; }
}
ToTable("ip");
HasKey(c => c.IpNumber);
Property(c => c.IpNumber).HasColumnName("ipcode");
Property(c => c.CustomerName).HasColumnName("displayname");
Reservation
public class ReservationDetail
{
public string ReservationId { get; set; }
public short TransactionLineNumber { get; set; }
...
public virtual ICollection<Customer> LinkedCustomers { get; set; }
}
ToTable("r_transaction_detail");
HasKey(rd => new { rd.ReservationId, rd.TransactionLineNumber });
Property(rd => rd.ReservationId).HasColumnName("reservation_id");
Property(rd => rd.TransactionLineNumber).HasColumnName("transaction_line_number");
Now for the question/problem
At runtime, I am attempting to get a list of reservations, and each of the related customers on a reservation. Running the following example code:
(this is an IQueryable of ReservationDetail) reservationItems.First().LinkedCustomers.First().CustomerName;
throws an exception on the second First() call because LinkedCustomers has no items. Looking at the DB I am connecting to, there should be one entry in this list of Customers.
Any pointers on where my configuration may be bad?