【问题标题】:Linq to Entities: How do I pass an IQueryable to a MethodLinq to Entities:如何将 IQueryable 传递给方法
【发布时间】:2010-02-08 19:43:30
【问题描述】:

我真的对这个感到困惑。我正在尝试将我的 posts 传递给一个方法。我该怎么做:

var posts = from p in context.post
            where (p.post_isdeleted == false && (object.Equals(p.post_parentid, null))
            select new
            {
                p.post_date,
                p.post_id,
                FavoriteCount = (from f in context.favorites
                                 where f.post.post_id == p.post_id
                                 select new { f }).Count()
            };


posts = QuestionList.FilterQuestion(posts, sort);

//the problem is here
//IQueryable is not the right type for posts. What type do I put in there
private static IQueryable FilterQuestion(IQueryable p, string sort)
{

【问题讨论】:

  • Linq 查询可能会有所简化。例如,FavoriteCount = p.post.favorites.count() 如果您的对象模型设置正确。

标签: entity-framework linq-to-entities iqueryable


【解决方案1】:
private static IQueryable<post> FilterQuestion(IQueryable<post> p, string sort)

【讨论】:

    【解决方案2】:

    您不能对匿名对象 (select new { }) 执行此操作。您必须在其中指定一个强类型,例如:

    var posts = from p in context.post
            where (p.post_isdeleted == false && (object.Equals(p.post_parentid, null))
            select new Post
            {
                Date = p.post_date,
                Id = p.post_id,
                FavoriteCount = (from f in context.favorites
                                 where f.post.post_id == p.post_id
                                 select new { f }).Count()
            };
    

    从这里,您可以使用@Luhmann 的答案和强类型 IQueryable。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      相关资源
      最近更新 更多