2012-07-18 27 views
0

我遇到此錯誤。 「實體或複雜類型'MvcApp.Models.Survey'不能在LINQ to Entities查詢中構建。」C#MVC Linq subquery實體或複雜類型'XXX'不能在LINQ to Entities查詢中構造

這是我的查詢:

 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(),但他們的視圖(surveys3)失敗時嘗試與foreach循環模式

我的模特教室看起來像這樣:

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; } 
    } 
+0

我也嘗試過使用annonimoues類的查詢,但視圖失敗說「傳遞到字典的模型產品類型的系統」。 Data.Entity.Infrastructure.DbQuery'1 [<> f__AnonymousType5'3 [System.Int64,System.String,System.String]]',但是這個字典需要一個'System.Collections.Generic.IEnumerable'類型的模型項[MvcApp.Models.Survey]'。 – Chris 2012-07-18 18:23:36

+0

您的視圖的模型是什麼? – Jorge 2012-07-18 18:23:49

+0

您好Jorge,感謝您的回答,我只是用模型更新我的問題 – Chris 2012-07-18 18:29:06

回答

0

這不應該起作用。相反,您可以考慮創建一個視圖模型來保存所需的字段(並將視圖更新爲該類型而不是調查),然後將其傳遞給視圖,或在之前調用ToList()創建新對象。例如:

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() 
              }); 

編輯: 重新閱讀你的問題,更新的代碼後,我真的覺得你想在這裏做的是創建一個視圖模型來保存您需要發送到視圖中的數據。您不想爲您正在做的事情創建新記錄,因此使用實體類來保存視圖需要的數據是濫用實體類的數據。如果您需要的ViewModels一些更多的信息,請閱讀本:

http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

相關問題