如何在 Entity Framework 和 EF Core 中使用 .Include()

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

是否可以以在 Entity Framework 6 和 EF Core 中都有效的方式使用 .Include()?

我目前有命令处理程序可以访问 IQueryable<> 但不知道它的来源,并且可以根据上下文更改来源 运行。例如 Entity Framework 6 在 运行 实际应用程序时使用,但 EF Core 用于测试(使用 SQLite In Memory 提供程序)

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
    }
}

以上在使用 Entity Framework 时工作正常,但在 运行 EF Core 时 .Include() 不起作用(注意 using System.Data.Entity);

如果将 using 语句更改为 using Microsoft.EntityFrameworkCore 则它在 运行 EF Core 而不是 Entity Framework 时有效。

有没有办法让框架不可知.Include()?或者至少同时支持 EF Core 和 Entity Framework?

您可以使用您自己的显式调用适当扩展方法的扩展方法来执行此操作:

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
    }
}

但这只有在编译时已知目标框架时才有效。