实体框架渴望加载第二级 - 不填充

时间:2015-06-01 20:43:52

标签: c# entity-framework eager-loading

以下是我的代码摘录

namespace QuizGame.Models
{

public class QuestionBank
{

    public QuestionBank()
    {
        Status = DeleteStatus.Active;
        Questions = new List<Question>();
    }
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Description { get; set; }

    public List<Question> Questions { get; set; }


}

public class Question 
{
    public Question()
    {
        Status = DeleteStatus.Active;
        QuestionType = Models.QuestionType.MultipleChoice_SingleAnswer_Text;
        PossibleAnswers = new List<Answer>();
    }



    [Key]
    public int Id { get; set; }

    [Required]
    public string QuestionText { get; set; }

    [Required]
    public QuestionType QuestionType { get; set; }

    public string Tags { get; set; }

    [Required]
    public List<Answer> PossibleAnswers { get; set; }

}

public class Answer
{
    public int Id { get; set; }

    public String Value { get; set; }

    public bool IsCorrect { get; set; }
 }

}

因此,尝试获取给定问题库的问题列表

以下似乎没有填充可能的答案

        var x = from g in _dc.QuestionBank
                    .Include (q => q.Questions)
                    .Include(q => q.Questions.Select(a => a.PossibleAnswers))
                where g.Status == DeleteStatus.Active &&
                g.Id == bankId
                select g.Questions;

我已经实现了一个真正的hacky解决方案

        var xl = new List<Question>();

        var ql = (from g in _dc.QuestionBank.Include(q => q.Questions)
                  where g.Status == DeleteStatus.Active &&
                  g.Id == bankId
                  select g.Questions).FirstOrDefault();


        foreach (Question item in ql.ToList())
        {
            var q1 = from q in _dc.Questions.Include(a => a.PossibleAnswers)
                     where q.Id == item.Id
                     select q;

            xl.Add(q1.FirstOrDefault());
        }

但我确信在急切的加载查询中我找不到一些小东西,它可以解决问题并使事情变得更清楚。

0 个答案:

没有答案