【发布时间】:2012-07-18 18:20:29
【问题描述】:
我遇到了这个错误。 “无法在 LINQ to Entities 查询中构造实体或复杂类型 'MvcApp.Models.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 循环模型时,View(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; }
}
【问题讨论】:
-
我也尝试在查询上使用 annonimoues 类,但视图失败说“传递到字典中的模型项的类型为'System.Data.Entity.Infrastructure.DbQuery
1[<>f__AnonymousType53[ System.Int64,System.String,System.String]]',但此字典需要“System.Collections.Generic.IEnumerable`1[MvcApp.Models.Survey]”类型的模型项。 -
你的视图模型是什么?
-
您好 Jorge,感谢您的回答,我只是用模型更新了我的问题
-
还有一件事,你认为它是强类型到什么模型的?
-
看起来问题出在 NumberOfQuestions 上。您是否尝试过进行更改以便获得完整的调查并让 NumberOfQuestion getter 返回 Questions.Count?
标签: c# asp.net-mvc linq count subquery