Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entity framework core reuse a set of include statements

How can I clean up my entity 'includes' to reuse the same set of statements? I'm trying to reuse a set of Includes while staying DRY.

Before

_context.Accounts
              .Include(x=> x.Status)
              .Include(x=> x.Type)
              .Include(x=> x.Phones)
              .Include(x=> x.Users)
              .Include(x=> x.Admins)

After:

_context.Accounts.CustomIncludes()
like image 380
Bryan Stump Avatar asked Aug 31 '25 21:08

Bryan Stump


1 Answers

Try this:

public static class DataExtensions
{
    public static Microsoft.EntityFrameworkCore.Query.IIncludableQueryable<Account, List<Admin>> CustomIncludes(this DbSet<Account> accounts)
    {
        return accounts
            .Include(p => p.Status)
            .Include(p => p.Type)
            .Include(p => p.Phones)
            .Include(p => p.Users)
            .Include(p => p.Admins);
    }
}

Then you can say

context.Accounts.CustomIncludes();
like image 169
J. Allen Avatar answered Sep 04 '25 22:09

J. Allen