Martin Wickman
Martin Wickman

Reputation: 19905

How to include multiple tables from the same table?

I have a bunch of simple tables/classes. It's zero-to-one relationship.

(Contact has one Type and one Account. Account has one Type, Category, PaymentMethod, Invoice. Keys etc omitted for brevity)

class Contact {
    Type MyType;
    Account MyAccount;
}

class Account {
    Type MyType;
    Category MyCategory;
    PaymentMethod MyPayment;
    InvoicingMethod MyMethod;
}

class Type {
     Guid id;
     string name;
}

class Category {
    Guid id;
    string name;
}

class PaymentMethod {
    Guid id;
    string name;
}

class InvoicingMethod {
    Guid id;
    string name;
}

How do I .include() this mess?

The code below is the only combination I could find which works, but it's verbose and weird:

context.Contacts.Where(...)
            .Include(c => c.MyType)
            .Include(c => c.Account)
              .ThenInclude(a => a.MyCategory)
            .Include(c => c.Account)         // Duplicated for next line
              .ThenInclude(a => a.MyType)
            .Include(c => c.Account)         // Duplicated for next line
              .ThenInclude(a => a.MyPayment)
            .Include(c => c.Account)         // Duplicated for next line
              .ThenInclude(a => a.MyMethod)

Any way to make this less verbose? Or even better, I'd rather just be telling EF to include whatever it needs to eager load all relations.

Having to include everything like this seems contra-productive and prone to errors, so I suspect there is an easier solution for this.

Upvotes: 1

Views: 472

Answers (1)

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

I can propose better Include usage:

await context.Contacts
            .Include(c => c.MyType)
            .Include(c => c.MyAccount.MyCategory)
            .Include(c => c.MyAccount.MyType)
            .Include(c => c.MyAccount.MyPayment)
            .Include(c => c.MyAccount.MyMethod)
            .ToListAsync();

Will update answer later if it is still needed syntax shown in question. I think it is possible to do something like that but implementation may take some time:

await context.Contacts
            .Include(c => c.MyType)
            .Include(c => c.MyAccount)
               .ThenIncludeInline(a => a.MyCategory)
               .ThenIncludeInline(a => a.MyType)   
            .ToListAsync();

Upvotes: 1

Related Questions