LINQ Query to inner join DbContext Entities to IQueryable

c# entity-framework linq

Question

I have two tables, 'Events' and 'Services', that have a one-to-many relationship (each event has at least one service).

I'm writing a C# console application that will extract a subset of events and then extract the corresponding services.

I have a method that extracts the events into an IQueryable<Event> object and it's working as expected. But when I join that IQueryable<Event> object to an IQueryable<Service> (as shown below) my resulting object contains references different contexts and I only want it to contain the IQueryable<Service> results.

Is there a better way to do this?

Here's my 'ExtractServices' method:

public IQueryable<Service> ExtractServices(IQueryable<Event> events)
{
    using (var preCertEntities = new PreCertEntities())
    {
        IQueryable<Service> services = from s in preCertEntities.Services
                                       orderby s.EventId
                                       select s;

        services = from s in services
                   join e in events on s.EventId equals e.EventId
                   select s;

        return services;
    }
1
0
5/9/2013 6:34:15 PM

Accepted Answer

You shouldn't need to extract child relationships like this - EF does it for you:

public IQueryable<Service> ExtractServices(IQueryable<Event> events)
{
    return events.SelectMany(e => e.Services).OrderBy(s => s.EventId);
}
2
5/9/2013 6:38:57 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow