views:

326

answers:

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;

    }

is 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?)

+2  A: 

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;
}
eu-ge-ne
+1  A: 

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

marc_s