ChevCast
ChevCast

Reputation: 59224

DbContext doesn't instantiate navigation property

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.

Upvotes: 0

Views: 619

Answers (2)

undefined
undefined

Reputation: 34299

In your above example you probably want something more like

var dataContext = new DataContext();
var testEntity = new TestEntity { Message = "Test message" };
var related = new RelatedTest { Something = true };
testEntity.RelatedTests = new List<RelatedTest>{related};
dataContext.TestEntities.Add(testEntity);
dataContext.SaveChanges();

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.

Upvotes: 1

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

Well, entity framework does not 'initialize' any of your objects (except with data ALREADY IN THE DATABASE). You have to do it yourself. EF only 'maps it to the database'.

Upvotes: 1

Related Questions