4

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() 
2
  • Put the includes in a custom extension method? Commented Jun 19, 2018 at 19:51
  • Can you show an example? Commented Jun 19, 2018 at 20:48

1 Answer 1

4

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Does not seem like reusing the include statements to me. It seems to me that it is put in an extension method but still starts from DbSet<Account>. If it would start from IQueryable<Account> that would seem like a possible reuse to me. Or is there another, different, DbSet<Account> on which that extension method could be applied?
ef core does not make it easy to reuse a set of includes given a dynamic starting point. IN order to get around that in my project, I created a thin wrapper to allow reusing includes regardless of the starting point. github.com/jasekiw/resuable-ef-core-includes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.