I have three tables: A, B, AtoB. A and B relate as may-to-many via the AtoB:
public class A
{
public int Id {get;set;}
public List<B> Bs {get;set;}
public List<AtoB> AtoBs {get;set;}
}
public class B
{
public int Id {get;set;}
public List<A> As {get;set;}
public List<AtoB> AtoBs {get;set;}
}
public class AtoB
{
public int AId {get;set;}
public int BId {get;set;}
public A Aa {get;set;}
public B Bb {get;set;}
}
My DbContext:
public class MyContext : DbContext
{
public DbSet<A> As {get;set;}
public DbSet<B> Bs {get;set;}
public DbSet<AtoB> AtoBs {get;set;}
}
in EF I have such a configuration for A:
public void Configure(EntityTypeBuilder<A> builder)
{
builder.HasMany(x => x.Bs)
.WithMany(x => x.As)
.UsingEntity<AtoB>(
x => x.HasOne(x => x.B)
.WithMany(x => x.AtoBs)
.HasForeignKey(x => x.BId)
.OnDelete(DeleteBehavior.Restrict),
x => x.HasOne(x => x.A)
.WithMany(x => x.AtoBs)
.HasForeignKey(x => x.AId)
.OnDelete(DeleteBehavior.Restrict)
);
}
Sometimes I load data in the following way:
var as = await _dbContext.As
.Include(x => x.Bs)
.ThenInclude(x => x.AtoBs)
.ToListAsync();
Next, when entities are loaded and the list is not empty, I get NRE exceptions, when performing such a query and accessing BId
property:
var filteredAs = as.Select(a => new { projected = a.AtoBs.FirstOrDefault().BId }).ToList();
Why does this happen? It seems like it occurs in the same time when entities are inserted to the tables. But if AtoB row is not yet inserted, then no Bs should be in the A…