2

我正在使用实体框架,我想了解如何从一个类和该类的子级获取数据。这是我的设置:

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

我设置了以下内容,因为我不希望对所有其他类进行延迟加载:

DbContext.Configuration.LazyLoadingEnabled = false;

这是我目前正在使用的代码:

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

我的存储库如下所示:

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

2 回答 2

3

.Include()您可以DbQuery通过调用或显式延迟加载来.Load()预先加载多个级别。DbEntityEntry.CollectionDbEntityEntry.Reference

例子

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();

这是一个有用的指南:http: //msdn.microsoft.com/en-us/data/jj574232

于 2013-06-26T06:34:12.877 回答
3

尝试在 .ToList(); 之前添加.Include("path" );

public IList<Question> GetQuestions(int subTopicId, int questionStatusId)
{
    var questions = _questionsRepository.GetAll()
        .Where(a => a.SubTopicId == subTopicId &&
                    a.QuestionStatusId == questionStatusId)
        .Include("...")
        .ToList();
    return questions; 
}
于 2013-06-26T06:34:26.003 回答