Using Include in a Generic Entity Framework Repository Saturday, March 3, 2018 5:28:00 PM

I was creating a generic repository (yes I'm still using that old pattern) with EntityFramework and I wanted to eager load child collections. One way to do this is to create different repository methods for each parent object and then hard code the Include in the different methods. Something like this:

context.SoftwareFiles.Include(s => s.Software);

or using strings

context.SoftwareFiles.Include("Software");

I had a generic GetFirst method that took a filter as an method parameter, so I added secoond parameter; a list of strings to hold my includes. Like so:

public virtual TEntity GetFirst<TEntity>(

Expression<Func<TEntity, bool>> filter = null, IList<string> incudes = null)

where TEntity : class

{

using (var context = new RedCarpetDBContext())

{

IQueryable<TEntity> query = context.Set<TEntity>();



if (filter != null)

{

query = query.Where(filter);

}

if (incudes != null)

{

foreach (var incude in incudes)

{

query = query.Include(incude);

}

}



return query.AsNoTracking().FirstOrDefault();

}

}



The method just itrerates through the includes and hydrates the child collections. You call it like this:

var includes = new List<string>();

includes.Add("OfferDetails");

var item = repo.GetFirst<OfferSummary>(x=> x.ASIN == asin, includes);



Hope someone finds this useful!