lundi 1 octobre 2018

linq async call to map to one object 2 tables with a foreign key

I know the title may sound awful, but is the best I could come up with. (Also my first question on stack:P)

I have reversed engineered a database and I have some classes looking like this:

public class Orders
{
    public int Id { get; set; }
    public int LocationId { get; set; }
    ...
    public Locations Location { get; set; }
    public Users User { get; set; }
}
public class Locations 
{
    public int Id { get; set; }
    ...
}

I also have 2 SQL tables "orders" and "locations" with a foreign key "LocationId"

If I am trying to do a select using LINQ like this:

var ordersResult = await _context.Orders.Where(o => <some condition>).ToListAsync();

Then it will fill my object with all the properties, excepting the Location object property which will be null. This makes sense, as I have made no join or anything like that.

I have no idea how do I have to writhe the LINQ statement so it will fill the entire object in only one async call without making multiple calls to the database.

I have also tried doing this:

var ordersResult = await _context.Orders.Join(_context.Locations,
                orders => orders.LocationId,
                locations=> locations.Id,
                (orders, locations) => new { Orders = orders, Locations = locations })
            .Where(orders_users => <some condition>)
            .Select(o => o.Orders)
            .ToListAsync();

but this still gives me a null for the Locations property.

Thanks in advance for your help!




Aucun commentaire:

Enregistrer un commentaire