EF 6,LINQ如何用条件参数创建里面包含的内容

时间:2017-11-07 07:36:25

标签: linq entity-framework-6

我有4张桌子

tblTraining
-----------
ID
Name

tblQuestion
----------
ID
Name
Active (true / false)
(FK) TrainingID

tblAnswer
----------
ID
Name
Active (true / false)
(FK) QuestionID

tblEmployeeTraining
-------------------------
ID
(FK) EmployeeID
(FK) TrainingID

每个培训都有很多问题,每个问题都有很多答案。 我还有tblEmployeeTraining来存储每个进行相关培训的员工。

我想通过培训ID获取培训对象, 但我有条件参数来包括问题或员工培训。

所以我在这里打电话给我的问题:

GetTraining(dbContext, ID: 1, includeEmployeeTrainings: true, includeQuestions: false);

这里我的GetTraining功能:

public static TrainingCourse GetTraining(dbContext, int ID = 0,
        bool includeEmployeeTrainings = false, bool includeQuestions = false)
    {
        try
        {
            IQueryable<tblTraining> training = (
                    from tc in dbContext.tblTraining
                    select tc);

            //where 
            if (ID != 0) training = training.Where(tc => tc.ID == ID);

            //include
            var includeQuestionQuery = includeQuestions ? training.Select(tc => new
            {
                Questions = tc.tblQuestions.Where(qq => qq.IsActive == true),
                Answers = tc.tblQuestions.Select(qq => qq.tblAnswers.Where(qa => qa.IsActive == true)),
            }) : null;

            var includeEmployeeTrainingsQuery = includeEmployeeTrainings ? training.Select(tc => new
            {
                EmployeeTrainings = tc.tblEmployeeTrainings.AsEnumerable()
            }) : null;

            training = training.Select(tc => new
            {
                tc,
                includeQuestionQuery,
                includeEmployeeTrainingsQuery,
            }).AsEnumerable().Select(tc => tc.tc).AsQueryable();

            return training.FirstOrDefault();
        }
        catch
        {
            throw;
        }
    }

如果我这样调用

,上面的代码将完美地运行
GetTraining(dbContext, 1, includeEmployeeTrainings: true, includeQuestions: true);

但如果我这样打电话会收到错误

GetTraining(dbContext, 1, includeEmployeeTrainings: false, includeQuestions: true);
  

无法创建类型为'System.Linq.IQueryable 1[[<>f__AnonymousType2 1 [[System.Collections.Generic.IEnumerable`1 [[.....]]'的空常量值。在此上下文中仅支持实体类型,枚举类型或基元类型

我知道错误是因为在GetTraining函数中,includeEmployeeTrainingsQuery为null。但是我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您的问题是,编译器无法计算匿名类型变量debug.print typename(Target.value) 中的null类型。

一种解决方案是使用ViewModels创建强类型结果。使用training之类的东西可以为null。或者您可以简单地避免使用经典if语句而不是三元运算符来赋值null:

(Viewmodelclass)null

所以现在你可以从顶部开始:

public class QuestionsQueryVm {
    public foo bar {get; set; }
}
public class EmplyeeTrainingVm {
    public foo bar {get; set; }
}


public class TrainingVm {
    public QuestionsVm  Questions { get; set;}
    public EmployeeTrainingsVm EmployeeTraining { get; set; }
    public Training Training
}