简体   繁体   中英

How can I get child data when Lazyloading is not enabled using Entity Framework 5?

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;
    }

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

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM