user441521
user441521

Reputation: 6998

Entity Framework Core Nullable FK not getting records

I have an OrderHeader table and OrderLines table. I also have a Rate table. Both OrderHeader and OrderLines can have rates. So this Rate table is setup as:

RateId
RateValue
OrderHeaderId
OrderLineId

So if we're adding header rates the OrderHeaderId is filled in and OrderLineId is null. When adding line rates the opposite happens.

My OnModelCreating() has:

modelBuilder.Entity<Rate>(entity =>
{
   entity.HasOne(d => d.OrderHeader)
      .WithMany(p => p.Rates)
      .HasForeignKey(d => d.OrderHeaderId)
      .HasContraintName("FK1")
      .IsRequired(false);

   entity.HasOne(d => d.OrderLines)
      .WithMany(p => p.Rates)
      .HasForeignKey(d => d. OrderLineId)
      .HasContraintName("FK2")
      .IsRequired(false);
}

When I query for a OrderLine record the Rates has 0 records in it, but in the DB there are 2 records for this OrderLineId.

I'm not really sure what else I should be looking for. I thought the .IsRequired(false) would have fixed the issue since in Rates table those FK's can have null values but it didn't.

Upvotes: 0

Views: 18

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89091

Related rows are only loaded if you request them, otherwise querying a single entity instance might load your whole database into memory. Read EF Core Loading Related Data

Also the FK between Rate and OrderLines should be on (OrderHeaderId,OrderLineId) to ensure that the Rate's OrderLines all belong to the Rate's OrderHeader. And for similar reasons the primary key of OrderLines should also be (OrderHeaderId,OrderLineId).

Upvotes: 1

Related Questions