这是我的存储库中的方法:
public List<Question> getallquestion()
{
var hej = from Core in db.CoreValue
join Question in db.Question on Core.CID equals question.QID
join Subject in db.SubjectType on Core.CID equals Subject.SID
select new
{
Core.Cname,
Question.QuestionText,
Subject.Sname
};
return hej.ToList();
}
这是错误:
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'NKI3.Models.Question'
此错误的解决方案是什么?我似乎无法找到它
我的CreateViewModel:
public class CreateViewModel
{
public string QuestionText { get; set; }
public string Sname { get; set; }
public string Cname {get;set;}
}
}
提前致谢!
最诚挚的问候!
答案 0 :(得分:5)
您的linq查询生成匿名对象列表(因为您使用select new { (...) }
而没有任何类型)。您应该将其替换为select new Question() { (...) }
。您应该根据Question类属性检查选择语法。
例如。当您拥有Name
时,Text
和Subject
属性应如下所示:
var hej = from c in db.CoreValue
join q in db.Question on c.CID equals q.QID
join s in db.SubjectType on c.CID equals s.SID
select new Question
{
QID = q.QID,
QuestionText = q.QuestionText
};
答案 1 :(得分:1)
您的方法期望返回Question
类型的集合,但您的LINQ查询返回anonymous type的序列。您应该更改查询,例如更改预测:
public List<Question> getallquestion()
{
var hej = from Core in db.CoreValue
join Question in db.Question on Core.CID equals question.QID
join Subject in db.SubjectType on Core.CID equals Subject.SID
select new Question
{
Name = Core.Cname,
Text = Question.QuestionText,
Subject = Subject.Sname
};
return hej.ToList();
}
这是使用object initializer从查询结果中分配Question
类型的属性值。您的房产名称会有所不同。
答案 2 :(得分:1)
将您的选择更改为如下所示:
public List<CreateViewModel> GetAllQuestionViewModel()
{
var hej = from Core in db.CoreValue
join Question in db.Question on Core.CID equals question.QID
join Subject in db.SubjectType on Core.CID equals Subject.SID
select new CreateViewModel
{
Cname = Core.Cname,
QuestionText = Question.QuestionText,
Sname = Subject.Sname
};
return hej.ToList();
}
在您的控制器中,您可以执行以下操作:
public ActionResult Index() {
IEnumerable<CreateViewModel> questions = someContext.GetAllQuestionViewModel();
return View(questions);
}
答案 3 :(得分:0)
您无法返回匿名类型。
创建一个类
public class QuestionResult
{
public string Core {get; set;}
public string Question {get; set;}
public string Subject{get; set;}
}
并使用它
public List<QuestionResult> getallquestion()
{
var hej = from Core in db.CoreValue
join Question in db.Question on Core.CID equals question.QID
join Subject in db.SubjectType on Core.CID equals Subject.SID
select new QuestionResult
{
Core = Core.Cname,
Question = Question.QuestionText,
Subject = Subject.Sname
};
return hej.ToList();
}