C#MVC Linq子查询实体或复杂类型';XXX和x27;无法在LINQ to实体查询中构造
我犯了这个错误。“无法在LINQ to Entities查询中构造实体或复杂类型‘MvcApp.Models.Survey’。” 这是我的疑问:C#MVC Linq子查询实体或复杂类型';XXX和x27;无法在LINQ to实体查询中构造,c#,asp.net-mvc,linq,count,subquery,C#,Asp.net Mvc,Linq,Count,Subquery,我犯了这个错误。“无法在LINQ to Entities查询中构造实体或复杂类型‘MvcApp.Models.Survey’。” 这是我的疑问: var surveys3 = (from s in db.Surveys where s.AccountId == appAcc.Id select new Survey {
var surveys3 = (from s in db.Surveys
where s.AccountId == appAcc.Id
select new Survey
{
Id = s.Id,
Title = s.Title,
Description = s.Description,
NumberOfQuestions = (from q in s.Questions
select q).Count()
}).ToList();
View(surveys3);
我试图将.ToList()更改为.AsEnumerable(),但在尝试使用foreach循环模型时,视图(surveys3)失败
我的模型类如下所示:
public class Survey
{
[Required]
[Key]
public long Id { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[DataType(DataType.DateTime)]
public DateTime CreatedOn { get; set; }
[NotMapped]
public Int32 NumberOfQuestions { get; set; }
public virtual ICollection<Question> Questions { get; set; }
[ForeignKey("AccountId")]
public ApplicationAccount Account { get; set; }
[Required]
public long AccountId { get; set; }
}
公共类调查
{
[必需]
[关键]
公共长Id{get;set;}
[必需]
[长度(100)]
公共字符串标题{get;set;}
[数据类型(DataType.multilitext)]
公共字符串说明{get;set;}
[数据类型(数据类型.日期时间)]
public DateTime CreatedOn{get;set;}
[未映射]
公共Int32 NumberOfQuestions{get;set;}
公共虚拟ICollection问题{get;set;}
[外汇钥匙(“账户ID”)]
公共应用程序帐户帐户{get;set;}
[必需]
公共长帐户ID{get;set;}
}
这不应该起作用。相反,您可以考虑创建一个VIEW模型来保存您需要的字段(并将视图更新为那种类型而不是调查),并将其传递给视图或在创建新对象之前调用Telistor()。例如:
var surveys3 = db.Surveys.Where( s => s.AccountId == appAcc.Id)
.ToList()
.Select( s =>
new Survey {
Id = s.Id,
Title = s.Title,
Description = s.Description,
NumberOfQuestions = (from q in s.Questions
select q).Count()
});
编辑:
在重新阅读您的问题和更新的代码之后,我真的认为您在这里要做的是创建一个ViewModel来保存需要发送到视图的数据。您不希望为正在执行的操作创建新记录,因为使用实体类来保存视图所需的数据是对实体类的滥用。如果需要有关ViewModels的更多信息,请阅读以下内容:
我还尝试在查询中使用annonimoues类,但视图无法说明“传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery
1[f_uAnonymousType5
3[System.Int64,System.String,System.String]],但此词典需要类型为“System.Collections.Generic.IEnumerable`1[MvcApp.Models.Survey]的模型项’。你的观点是什么样的?你好,Jorge,谢谢你的回答,我刚刚用这个模型更新了我的问题。还有一件事,你的观点是强类型的,是什么模型?看起来问题是NumberOfQuestions。你有没有尝试过改变一些东西,这样你就可以得到完整的调查,让NumberOfQuestion getter返回问题。计数?