2

I am using ASP.net MVC with C#. Why this is code:

public IQueryable<Product> ListProducts(string prodcutType)
{
    var results = from p in db.Products
        join s in db.Stocks
        on p.ID equals s.IDProduct
        where p.ptype == prodcutType
        select new { s.width, s.height, s.number};                 
    return results;
}

showing the following error?

Error 1 Cannot implicitly convert type System.Linq.IQueryable<AnonymousType#1> to System.Linq.IQueryable<eim.Models.Product>. An explicit conversion exists (are you missing a cast?)

0

2 Answers 2

8

Because select new { s.width, s.height, s.number} means System.Linq.IQueryable<AnonymousType#1> but your function expects to return IQueryable<Product>. Change your code to:

public IQueryable<Product> ListProducts(string prodcutType)
{

    var results = from p in db.Products
                  join s in db.Stocks
                  on p.ID equals s.IDProduct
                  where p.ptype == prodcutType
                  select p;
    return results;
}

UPDATED:

Or maybe you want IQueryable<Stock>:

public IQueryable<Stock> ListProducts(string prodcutType)
{

    var results = from p in db.Products
                  join s in db.Stocks
                  on p.ID equals s.IDProduct
                  where p.ptype == prodcutType
                  select s;
    return results;
}

If you want only 3 properties width+height+number create new type. For example:

public class SomeType {
    public int Width { get; set; }
    public int Height { get; set; }
    public int Number { get; set; }
}

public IQueryable<SomeType> ListProducts(string prodcutType)
{

    var results = from p in db.Products
                  join s in db.Stocks
                  on p.ID equals s.IDProduct
                  where p.ptype == prodcutType
                  select new SomeType {
                      Width = s.width,
                      Height = s.height,
                      Number = s.number
                  };
    return results;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The last line of your LINQ query

select new { s.width, s.height, s.number};     

will select only these three fields from your table "db.Stocks", and this creates a new, anonymous type, which is what gets stored in "results" and passed back.

What you're passing back in the "return results;" statement therefore isn't a IQueryable<Product> - it's something totally different (that IQueryable of an anonymous type).

If you want to return products, you'll need to cast that anonymous type to a "Product" (or create a new product class from the fields selected).

Marc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.