简体   繁体   中英

LINQ Query to inner join DbContext Entities to IQueryable

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;
    }

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM