2

I am using Entity Framework and I would like to find out how to get data from a class and a child of the class. Here is my setup:

 public class Question
 {
    public Question()
    {
        this.Answers = new List<Answer>();
    } 
    public int QuestionId { get; set; }
    ...
    ...
    public string Title { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
}

public class Answer
{
    public int AnswerId { get; set; }
    public string Text { get; set; }
    public int QuestionId { get; set; }
    public virtual Question Question { get; set; }
}

I have set the following as I don't want Lazyloading for all the other classes:

DbContext.Configuration.LazyLoadingEnabled = false;

Here is the code I am currently using:

    public IList<Question> GetQuestions(int subTopicId, int questionStatusId)
    {
        var questions = _questionsRepository.GetAll()
            .Where(a => a.SubTopicId == subTopicId &&
                        a.QuestionStatusId == questionStatusId)
            .ToList();
        return questions; 
    }

My repository looks like this:

    public virtual IQueryable<T> GetAll()
    {
        return DbSet;
    }

2 Answers 2

3

Try adding .Include("path") before .ToList();

public IList<Question> GetQuestions(int subTopicId, int questionStatusId)
{
    var questions = _questionsRepository.GetAll()
        .Where(a => a.SubTopicId == subTopicId &&
                    a.QuestionStatusId == questionStatusId)
        .Include("...")
        .ToList();
    return questions; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Do I just put the word "predicate" or should that be the property name? What about if there is more than one child?
The property name. You can add as many .Include() as you want. Just see the property from within the standard (start) class. Ex.: .Include("foo").Include("foo.bar") -> bar is a property in class foo and foo is a property in the class you are getting from the database.
3

You can eager load multiple levels by using .Include() in your DbQuery or explicitly lazy load by calling .Load() on the DbEntityEntry.Collection or DbEntityEntry.Reference.

Example

context.MyParentEntities.Include(x=>x.ChildEntities); //eager load

//explicit collection property lazy load
context.Entry(MyEntity).Collection(x=>x.ChildEntities).Load();
//explicit reference property lazy load
context.Entry(MyEntity).Reference(x=>x.ChildEntity).Load();

Here is a useful guide : http://msdn.microsoft.com/en-us/data/jj574232

1 Comment

I gave you an upvote. I guess the downvoter is too shy to answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.