2011-08-31 161 views
0
public IEnumerable<Models.Comment> GetUserComments() 
{ 
    return List<Comment> 
    { 
     new Comment 
     { 
      CommentFor = "ee", 
      DateAdded = DateTime.Now, 
      CommentText = "aaaa", 
      Location = new Location 
      { 
       Name = "Location Name", 
       Country = new Country 
       { 
        Name="Israel" 
       }, 
       State=new State { Name="TelAviv" } 
      } 
     } 

    }; 
} 

你能幫我糾正Linq查詢嗎?實體框架4.0與Linq

我需要使用實體框架4.
我不喜歡這個

  public IEnumerable<Models.Comment> GetUserComments() 
    { 
     var comment = (from u in context.Comments 
         where u.UserID == userId 
         select new Comment 
         { 
          //Location = context.Locations.FirstOrDefault(x => x.locationid == u.LocationID).name, 
          Location = (from l in context.Locations 
             where l.LocationID == u.LocationID 
             select new Location 
             { 
              Name = l.Name, 
              State = (
               from s in context.States 
               where (s.StateID == l.StateID) 
               select new State { Name = s.Name } 
               ).FirstOrDefault() 

             } 
             ).FirstOrDefault(), 
          CommentFor = "bs", 
          DateAdded = u.DateAdded, 
          CommentText = u.CommentText 
         } 
        ).ToList(); 
         } 

喜歡把自己的錯誤採取從數據庫值:

實體或複雜類型「CGWeb.Models.Repositories .Comment'不能在LINQ to Entities查詢中構造。

請告訴我,我的錯誤,我做了

+0

並請花一些時間來正確地格式化代碼(見我的更新)。 – Steven

回答

2

u.Location應該是Location

+0

我確實喜歡這個..現在解決了這個問題。感謝快速重放..但還有其他問題。像這樣:實體或複雜類型'CGWeb.Models.Repositories.Comment'不能在LINQ to Entities查詢中構造。 – Justinonday

2
    select new Comment 
        { 
         u.Location //<- remove the u. 
+0

好的。這是一個問題。現在解決了......但現在出現錯誤。實體或複雜類型'CGWeb.Models.Repositories.Comment'不能在LINQ to Entities查詢中構造。 – Justinonday

+1

如果「評論」是來自您的模型的實體,您將會遇到此問題。您必須在預測中使用匿名類型或未映射類型。 –

+0

好的。你可以指定你的意思是「匿名類型」..在那裏需要什麼解決方案..?請分享 – Justinonday

0

試試這個

var comment = (from u in context.Comments 
          where u.UserID == userId 
          select new Comment 
          { 
           Location = context.Locations.FirstOrDefault(x=>x.LocationID==u.LocationID).Name,           
           CommentFor = "Bb", 
           DateAdded = u.DateAdded, 
           CommentText = u.CommentText 
          } 
         ).ToList(); 
+0

先生我得到新的錯誤。請檢查我的問題 – Justinonday