我正在尝试以下方法:
var questions = _questionsRepository
.GetAll()
.Where(q => q.Problem.SubTopicId == subTopicId || subTopicId == 0)
.Where(q => q.QuestionStatusId == questionStatusId || questionStatusId == 0)
.Where(q => q.AssignedTo == assignedTo || assignedTo == "0")
.Where(q => q.ModifiedBy == modifiedBy || modifiedBy == "0")
.Include(q => q.Problem)
.Include(q => q.Answers)
.Select(x=>new Question {
QuestionId = x.QuestionId,
QuestionUId = x.QuestionUId,
Answers = x.Answers,
Problem = new Problem {
ProblemId = x.Problem.ProblemId
}
}).ToList();
但收到错误消息说:
System.NotSupportedException was unhandled by user code
HResult=-2146233067
Message=The entity or complex type 'Models.Contexts.Question' cannot be constructed in a LINQ to Entities query.
Source=EntityFramework
StackTrace:
答案 0 :(得分:1)
您的类问题似乎不是存储库/上下文的一部分,因此EF无法在SQL中构造此类的对象。但是,您可以在SQL中获取所有必需的数据,并在获得所有数据后在.net中构造对象。要指示此switch-to-.net,您可以使用AsEnumerable()方法。
var questions = _questionsRepository
.GetAll()
.Where(q => q.Problem.SubTopicId == subTopicId || subTopicId == 0)
.Where(q => q.QuestionStatusId == questionStatusId || questionStatusId == 0)
.Where(q => q.AssignedTo == assignedTo || assignedTo == "0")
.Where(q => q.ModifiedBy == modifiedBy || modifiedBy == "0")
.Include(q => q.Problem)
.Include(q => q.Answers)
.Select(x => new {
QuestionId = x.QuestionId,
QuestionUId = x.QuestionUId,
Answers = x.Answers,
ProblemId = x.Problem.ProblemId
})
.AsEnumerable()
.Select(x => new Question {
QuestionId = x.QuestionId,
QuestionUId = x.QuestionUId,
Answers = x.Answers,
Problem = x.ProblemId
})
.ToList();
答案 1 :(得分:1)
与实体The entity cannot be constructed in a LINQ to Entities query重复。查看此帖子以了解您无法直接在您的选择关闭中实例化实体。您必须创建一个DTO类来使用。
解决方案也是:
var questions = _questionsRepository
.GetAll()
.Include("Problem")
.Include("Answers")
.Where(q => (q.Problem.SubTopicId == subTopicId || subTopicId == 0)
&& (q.QuestionStatusId == questionStatusId || questionStatusId == 0)
&& (q.AssignedTo == assignedTo || assignedTo == "0")
&& (q.ModifiedBy == modifiedBy || modifiedBy == "0")).ToList();
你应该得到你想要的东西。