C# 无法隐式转换类型System.Collections.Generic.List<&书信电报;匿名类型:int、string、bool>&燃气轮机;
这是我的代码:C# 无法隐式转换类型System.Collections.Generic.List<&书信电报;匿名类型:int、string、bool>&燃气轮机;,c#,asp.net,asp.net-core-3.1,C#,Asp.net,Asp.net Core 3.1,这是我的代码: var answers = await (from a in _context.Answers where a.QuestionId == quest.Id select new { a.Id, a.Name, a.IsRight }).ToListAsync(); var view = new QuestionViewModel() {
var answers = await (from a in _context.Answers
where a.QuestionId == quest.Id
select new { a.Id, a.Name, a.IsRight }).ToListAsync();
var view = new QuestionViewModel()
{
Id = quest.Id,
Name = quest.Name,
Scores = quest.Scores,
CategoryId = cate.Name,
Answers = answers // Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: int Id, string Name, bool IsRight>>' to 'System.Collections.Generic.List<eWebHotelSolution.Data.Entities.Answer>'
};
var answers=await(从上下文中)。answers
其中a.QuestionId==quest.Id
选择新的{a.Id,a.Name,a.IsRight}).toListSync();
变量视图=新问题视图模型()
{
Id=quest.Id,
Name=quest.Name,
分数=任务。分数,
CategoryId=类别名称,
Answers=Answers//无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”
};
QuestionViewModel中的属性:
public string Id { get; set; }
public string Name { get; set; }
public decimal Scores { get; set; }
public string CategoryId { get; set; }
public List<Answer> Answers { get; set; } = new List<Answer>();
publicstringid{get;set;}
公共字符串名称{get;set;}
公共十进制分数{get;set;}
公共字符串CategoryId{get;set;}
公共列表回答{get;set;}=new List();
我只想要“问题”表的详细记录。它将包含“Answers”表的整个记录列表,其中外键等于“Questions”表的主键,并仅检索我在“Answers”中选择的列。您正在创建一个名为Answers的匿名类型的新列表(请检查您的
var Answers
以了解特定类型!)由于您使用投影查询,请选择新的{a.Id、a.Name、a.IsRight}
。无法将其转换为类型应答
只需使用此
var answers = await _context.Answers
.Where(a=> a.QuestionId == quest.Id)
.Select( a=> new Answer
{
Id=a.Id,
Name= a.Name,
IsRight = a.IsRight
}).ToListAsync();
在linq查询中使用新答案{}而不是新答案{}。谢谢你,lujcon,我尝试了它并得到了想要的结果。我的选择:
var answers=wait(从a.QuestionId==quest.Id的{u context.answers中选择新答案{Id=a.Id,Name=a.Name,IsRight=a.IsRight})。ToListSync()代码>是的,它也会工作。只是不同的语法。但大多数人更喜欢lambda,因为它通常较短。这就是我改变它的原因。