Search code examples
entity-framework-4wcf-ria-services

EF How to relate already loaded entities?


I have the following methods on the server (RIA services):

public IQueryable<Customer> GetCustomers()
{
    return ObjectContext.Customers;
}

public IQueryable<Customer> GetCustomersWithInvoicesAndInvoiceItemsAsync()
{
    return ObjectContext.Customers
        .Include("Invoices.InvoiceItems");
}

These items are loaded on client as IEnumerable<>, lets name the CollectionA and CollectionB. My problem is next: If I add/remove a Customer in CollectionA, CollectionB will not be aware of it. Editing is working as expected, since both of collections contain same entities. Is there a way I can load Invoices separately, and relate them in the client, so I would work only on one collection of customers, and not two?


Solution

  • Service-side (beside the GetCustomers method):

    public IQueryable<Invoice> GetInvoicesAndInvoiceItemsAsync()
    {
        return ObjectContext.Invoices.Include("InvoiceItems");
    }
    

    Client-side, after getting customers and invoices in separate calls (as IEnumerables):

    var query = customers.Join(invoices, c => c.CustomerId, i => i.CustomerId,
        (c,i) => Tuple.Create(c, i) );
    

    This will give you a list of Customer - Invoice pairs. Or use GroupJoin:

    var query = customers.GroupJoin(invoices, c => c.CustomerId, i => i.CustomerId,
        (c,i) => Tuple.Create(c, i) );
    

    This will give you a list of Customer - Invoices (plural) pairs.