Automatically Including Complex Properties with EntityFramework

Recently I found it necessary to generalize code related to “including” complex properties when using the Entity Framework and lazy loading. For anyone that has done composition with the Entity Framework, especially in aspnetcore, knows how much of a pain it can be to get data out and into JSON. This is how I tackled the problem.

The first step is to create an attribute that we can use on properties to signify that they should be included when pulling data from the database. I have called this EagerIncludeAttribute.

public class EagerIncludeAttribute : Attribute { }

Personally, I try to deal directly with DbContext instances because the methods provided are incredibly generic. To apply this to our DbContext, we can use the Set method along with the Include extensions to achieve autonomous behavior. Note that this only includes first level properties and may be overridden by JsonIgnore attributes.

public IEnumerable<TModel> Get<TModel>() {
    var type = typeof(TModel);
    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    // _dataContext in this is a custom class inheriting DbContext
    IQueryable<TModel> set = _dataContext.Set<TModel>();

    foreach(var propInfo in props) {
        if(propInfo.GetCustomAttribute<EagerIncludeAttribute>() != null) {
            set = set.Include(propInfo.Name);
            // here is where you would do a recursive sub-property include...

    return set;

You can modify this in a number of ways to suit your needs, but the basic idea is that you can use attribute based programming to achieve eager loaded properties without requiring custom loads for each type. Happy coding!

There are no comments.

Leave a Reply