How to use .Include() in Entity Framework and EF Core

Nick Williams picture Nick Williams · Aug 15, 2018 · Viewed 7.5k times · Source

Is it possible to use .Include() in a way which works in both Entity Framework 6 and EF Core?

I currently have command handlers which have access to an IQueryable<> but don't know the source of it, and the source can be changed depending on the context running. For example Entity Framework 6 is used when running the actual application, but EF Core is used for test (using the SQLite In Memory provider)

using System.Data.Entity;

class DemoCommandHandler
{
    public void Handle(IQueryable<Blog> blogsQueryable, DemoCommand command)
    {
        //Need to get the blog and all the posts here
        var blogs = blogsQueryable.Include(b => b.Posts).Single(b => b.Id = command.BlogId);

        //Do stuff with blog and posts
    }
}

The above works fine when using Entity Framework but the .Include() does not work when running EF Core (note the using System.Data.Entity);

If the using statement is changed to using Microsoft.EntityFrameworkCore then it works when running EF Core but not Entity Framework.

Is there a way to make a framework agnostic .Include()? Or at least supporting both EF Core and Entity Framework?

Answer

CodeCaster picture CodeCaster · Aug 15, 2018

You could do so using your own extension method that explicitly calls the appropriate extension method:

public static class EntityFrameworkExtensions
{
    public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path)
        where T : class
    {
        #if NETCOREAPP2_0
        return Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.Include(source, path);
        #else
        return System.Data.Entity.DbExtensions.Include(source, path);
        #endif
    }
}

But this would only work if the target framework is known at compile time.