I have a scenario where I'm inserting quite a few related entities into the database with lazy-loading disabled. In one case I initialize the entity and then insert it as so:
// SomeObj is an entity with an identity specification in its primary key column.
var obj = new SomeObj
{
SomeTypeId = 1,
SomeOtherTypeId = 185,
};
context.SomeObjs.Add(obj);
context.SaveChanges();
What I'm noticing is that in the context of my application when this happens SomeOtherType (the navigation property which SomeOtherTypeId is the foreign key of) is initialized while SomeType is not initialized.
Both navigation properties are defined using the FluentAPI in the same way:
entity.HasOne(d => d.SomeType)
.WithMany(p => p.SomeObjs)
.HasForeignKey(d => d.SomeTypeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_SomeObj_SomeType");
entity.HasOne(d => d.SomeOtherType)
.WithMany(p => p.SomeObjs)
.HasForeignKey(d => d.SomeOtherTypeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_SomeObj_SomeOtherType");
I hopped into LINQPad to see if I could reproduce this half-initialization of navigation properties on insert and I could not. Inserting a single entity of SomeObj type in LINQPad resulted in NONE of the navigation properties being initialized (which seems more reasonable than half of them being initialized).
So this got me to wondering: when are navigation properties actually initialized in EF Core 3.1? As noted above, lazy-loading is disabled (which is why it is reasonable to me that all of the navigation properties are null).
I can work around this by following up the insert with:
obj = context.SomeObjs
.Include(o => o.SomeType)
.Include(o => o.SomeOtherType)
.First(o => o.Id == obj.Id);
But this is only one small example in a larger code base and it seems more like there's something I'm missing.
Any help would be appreciated.