Saturday, August 13, 2011

ProxyCreationEnabled = false; can not load the collections

When using

this.Configuration.ProxyCreationEnabled = false;

You will not be able to load all child collections of an entity

var query = questionRep.All.Where(x => x.QuestionId == questionId);
retrievedQuestion = query.Single();
Assert.AreEqual(expectedCount, retrievedQuestion.Answers.Count);


The retrievedQuestion.Answers is left null when you set ProxyCreationEnabled to false. That assertion will throw an exception.


If you want then to populate the collections of an entity yet you don't want proxy creations, you need to eager load the collections manually.

var query = questionRep.All.Where(x => x.QuestionId == questionId);

query = query.Include("Answers");
query = query.Include("Comments");
query = query.Include("Answers.Comments");

retrievedQuestion = query.Single();

Assert.AreEqual(expectedCount, retrievedQuestion.Answers.Count);


retrievedQuestion.Answers will not be null anymore, Assert.AreEqual can now do its job.

No comments:

Post a Comment