Retrieving elements from a join with into Entity Framework

Viewed 34

I have this code:

private IQueryable<Trip> GetTripWithBreaksAndPassengers(DB_Context context, long id)
{
    return from t in context.trip
           where t.Id == id
           join breaks in context.breaks on t.Id equals breaks.tripid into breaksJoin
           join drivers in context.drivers on t.Id equals drivers.tripid into driversJoin
           select new Trip() { TripBreaks = ?, TripDrivers = ?};
}

For my Trip specified by an id, I want to return a list of Breaks and Drivers.

My Trip object has two fields which are lists, TripBreaks and TripDrivers:

public virtual List<TripBreak> TripBreaks { get; set; }
public virtual List<TripDriver> TripDrivers { get; set; }

I want both of them to be returned as part of a Trip - I am expecting breaksJoin and driversJoin to hold those specific results, but if queried like

TripDrivers = driversJoin.ToList()

it will throw an error.

How should I use those join results to get the elements held?

1 Answers

Explicit joins in a EF project are a code smell.

You should be able to use navigation properties and Include() to get the data you want, something like this.

var result = context.trip.Include(t => t.Breaks).Include(t => t.Drivers).FirstOrDefault(t => t.Id == id);

This will get you all the related entities in one go.

Adjust property names accordingly, since you didn't share your model classes.

Related