I created two entities with a simple 1 to many relationship.
public class TestEntity
{
public int Id { get; set; }
public string Message { get; set; }
public virtual ICollection<RelatedTest> RelatedTests { get; set; }
}
public class RelatedTest
{
public int Id { get; set; }
public bool Something { get; set; }
public virtual TestEntity TestEntity { get; set; }
}
When I go to test this the ICollection navigation property isn’t instantiated. I can’t add a related entity.
var dataContext = new DataContext();
var testEntity = new TestEntity { Message = "Test message" };
var related = new RelatedTest { Something = true };
testEntity.RelatedTests.Add(related); //fails on this line because RelatedTests is null.
dataContext.TestEntities.Add(testEntity);
dataContext.SaveChanges();
Is that the expected functionality? Do I have to instantiate the navigation property? I expected Entity Framework to instantiate the collection for me.
In your above example you probably want something more like
as you are creating the base entity so EF hasnt yet gotten its hands on the entity to do any fixups.
When you reload this entity from the database the collection shouldn’t be null in your above example as you appear to be using lazy loading.