0
votes

Hi I'm development a Web API in C# with entity framework, I have 4 tables in my database

Products: 
    IdProduct, 
    IdCategory, 
    IdBrand, 
    Product, 
    Price, 
    Descryption, 
    IdOffice

Category: 
    IdCategory, 
    Category

Brand: 
    IdBrand, 
    Brand

Office: 
    IdOffice, 
    Office

And I did a Web API with the Products model but I want to show the data and not the Id.

This is what I have done but gives me an error in the return

Cannot implicitly convert type 'System.Linq.IQueryable' anonymous type int IdProducto, string Category, string Product, string Brand, string office, string Description, decimal? Price' in System.Linq.IQueryable NameProject

private ExamenPOO1Entities db = new ExamenPOO1Entities();
private ExamenPOO1Entities1 ca = new ExamenPOO1Entities1();
private ExamenPOO1Entities2 ma = new ExamenPOO1Entities2();
private ExamenPOO1Entities3 su = new ExamenPOO1Entities3();

// GET: api/Productoes
public IQueryable<Producto> GetProductos()
{
    var query =
        from p in db.Productos
        join c in ca.Categorias
        on p.IdCategoria equals c.IdCategoria
        join m in ma.Marcas 
        on p.IdMarca equals m.IdMarca
        join s in su.Sucursales
        on p.IdSucursal equals s.IdSucursal
        select new 
        { IdProducto =p.IdProducto, Categoria = c.Categoria1, Producto = p.Producto1,
            Marca = m.Marca1, Sucursal = s.Sucursal, Descripcion = p.Descripcion,
            Precio = p.Precio};
        return query;
}
1
Please post the error message. - Christoph
Unrelated, but ouch about 4 db contexts - this means joins are done in memory. Are you sure you cant reduce these? - StuartLC
Ugh, joining across contexts is nasty for sure. Maybe it's that giving you the errors? We don't know unless you tell us what you error is... - DavidG
After new keyword, type Producto. - Saeed Bolhasani
Cannot implicitly convert type 'System.Linq.IQueryable' <<anonymous type int IdProducto, string Category, string Product, string Brand, string office, string Description, decimal? Price>>' in System.Linq.IQueryable <NameProject> - Eduardo Noyola

1 Answers

2
votes

You are having this error because as you specified, your method must return a IQueryable<Producto> but instead you're returning an anonymous object when you use the code below

select new {
     IdProducto =p.IdProducto, 
     Categoria = c.Categoria1, 
     Producto = p.Producto1,
     Marca = m.Marca1, 
     Sucursal = s.Sucursal, 
     Descripcion = p.Descripcion,
     Precio = p.Precio
}

So in order to be consistent with the method's signature the select should create a new Producto

select new Producto
    { ... }