Linq help - newbie

how it works

public IQueryable<Category> getCategories(int postId)  
{
      subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
      subnusMVCRepository<Post_Category_Map> postCategoryMap = new  subnusMVCRepository<Post_Category_Map>();

      var query = from c in categories.GetAll()
                  join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
                  where pcm.PostId == 1
                  select new Category
                  {
                    Name = c.Name,
                    CategoryId = c.CategoryId
                  };
       return query;
}

      

But it is not

public IQueryable<Category> getCategories(int postId)  
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();

    var query = from c in categories.GetAll()
                join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
                where pcm.PostId == postId
                select new Category
                {
                    Name = c.Name,
                    CategoryId = c.CategoryId
                };
    return query;
  }

      

0


source to share


2 answers


The problem is most likely in the implementation of the query provider.

pcm.PostId == 1

and

pcm.PostId == postId



really make a big difference. In the expression tree, the first is generated as a ConstantExpression, which does not need to be questioned.

In the second case, the compiler actually creates an inner class here (this is the _DisplayClassX you see). This class will have a property (most likely the same name as your parameter) and the expression tree will create a MemberAccessExpression that points to the autogenerator DisplayClassX. When you query the provider, it is necessary to compile () the Lambda expression and evaluate the delegate to get the value to be used in your query.

Hope it helps.

cosullivan

+3


source


The problem is not linq itself, you have to be sure the context or the provider object can retrieve the data. try to check

subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();

      

and see if they are full or if they behave as needed.

you can find the generated code for c__DisplayClass1 and see what you see there. multiple times generated code dose causes some strange things.



when you step into the code, check the locale and variable values. it might give you some hints as well.

Edit: Have you tried returning the List <> collection? or Enumerated type?

Edit: What is the real type of elementand the query cannot be iterable

0


source







All Articles