开发者

What is the underlying type of the result from a Linq to Entities query?

for example,

var result = from category in myEntities.Categories
                     where category.UserId == userId
                     orderby category.CategoryName
                     select category;

What is the type of "result"? I casted it to an IQueryable variable and it worked except it did not have some of the methods normally available, e.g. Count(). In my program I have to cast it to some explicit typ开发者_开发知识库es and then use the Count() method. What should I do?


You should use it as an IQueryable<Category>, which is its compile-time type.

At runtime, it will be an ObjectQuery<Category>. However, you should not use that.


Use this:

IQueryable<Category> categories = from x category in myEntities.Categories
                                  where category.UserId == userId
                                  orderby category.CategoryName
                                  select category;

I don't see why count would be unavailable in this scenario. Maybe if you were casting to plain IQueryable and not IQueryable<Category>?

EDIT: Just tested it. It's definitely because you used a generic IQueryable without a type. .Count() is not available when you use that. You must include the type.

EDIT2: If you are creating an anonymous type then you have to use the var keyword. You will need to create a type in order to cast it.

Create a custom type like this:

public class MyCustomType
{
     public string CategoryName { get; set; }
     public int UserId { get; set;}
}

Then instantiate your enumerable of custom types like so:

IEnumerable<MyCustomType> myCustomTypes = from x category in myEntities.Categories
                                          where category.UserId == userId
                                          orderby category.CategoryName
                                          select new MyCustomType { CategoryName = category.CategoryName, UserId = category.UserId };

You cannot use IQueryable when doing this as IQueryable allows you to send expression trees to the datasource. myEntities.Categories implements IQueryable so the query we just listed is executed at the source, but further queries on your IEnumerable<MyCustomType> Will be executed on the objects in memory.


As an addition to the other answers, you can also use the AsQueryable() method to get an IQueryable object that will have all the usual Linq query methods on it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜