user543489
user543489

Reputation: 101

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Linq.IQueryable'

I want to define a function containing a Linq query as bellow:

public IQueryable GetBasket(Guid userId)
{
    DabbaghanDataContext db = new DabbaghanDataContext();

    int rowNo = 0;
    var query = (from c in db.Carts
                 join co in db.CartOrders on c.Id equals co.Cart_Id
                 join p in db.Products on co.Product_Id equals p.Id
                 where c.UserId == userId && c.Issued == false
                 select new
                 {
                     co.Quantity,
                     co.TotalPrice,
                     p.Code,
                     p.Price,
                     p.Thumbnail
                 }).AsEnumerable().Select(r => new
                 {
                     RowNumber = ++rowNo,
                     Quantity = r.Quantity,
                     TotalPrice = r.TotalPrice,
                     Code = r.Code,
                     Price = r.Price,
                     Thumbnail = r.Thumbnail
                 });

    return query;
}

I get error

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'.

on the return query line.

What is the problem? How can I solve this problem? Please help.

Upvotes: 0

Views: 1229

Answers (2)

It'sNotALie.
It'sNotALie.

Reputation: 22794

In return query; change that to return query.AsQueryable(); And also try to change the method signature to use IQueryable instead of the nongeneric one

Upvotes: 0

driis
driis

Reputation: 164291

Your problem is the call to AsEnumerable- It converts the IQueryable to a IEnumerable; and therefore, you cannot return it as an IQueryable.

Correct me if I am wrong, but the second select seems to only add the row number to the result. You might as well want to do that together with the initial select, and skip the call to AsEnumerable().

Possible solutions: Rewrite the query to not use AsEnumerable (if you want an IQueryable returned), or you could change the return type to be IEnumerable, if that is a better fit for your problem.

Upvotes: 1

Related Questions