Forcefield Forcefield - 3 months ago 27
ASP.NET (C#) Question

Fill correctly a IQueryable model with linq join

I have to show data on a

listview
item, so I have the following code behind:

public IQueryable mostrarMesas()
{
var query = from area in db.res_areas_sucursal
join mesa in db.res_mesas_sucursal on area.area_gkey equals mesa.area_gkey
select mesa;

return query;
}


This joins two tables data and returns the data I need, but I need to show data from both tables, I tried creating this model that I think has what I need

public class Mesas
{
[Key]
public long? mesa_gkey { get; set; }

public String descripcion_mesa { get; set; }

public res_areas_sucursal res_areas_sucursal { get; set; }

public int total_capacidad { get; set; }

public bool disponible_para_reserva { get; set; }
}


But I don't know how to assign the query to return a list of
Mesas
objects instead of the ones from the entity framework. I'm using ASP.NET Webforms 4.5

How could I do this?

Should I establish the relations on the database first?

Answer

You can use anonymous types:

var query = from area in db.res_areas_sucursal
            join mesa in db.res_mesas_sucursal on area.area_gkey equals mesa.area_gkey
            select new { area, mesa } ;
            return query;

Or you can use your model:

var query = from area in db.res_areas_sucursal
                join mesa in db.res_mesas_sucursal on area.area_gkey equals mesa.area_gkey
                select new Mesas()
                {
                   mesa_gkey = mesa.gkey,
                   // continue the rest
                };

                return query;

Inside the select, you can use both area and mesa. Then you can select whatever properties (columns) you need and assign them.

Note that it is better to return IQueryable<Mesas> instead of just IQueryable unless you have a valid reason not to do so.

Comments