2011-08-31 293 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