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

3

是否可以使用.Include()方法,使其在Entity Framework 6和EF Core中均可使用?

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

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两者?


1
你的问题解答了我的问题 - “如果将using语句更改为using Microsoft.EntityFrameworkCore,则在运行EF Core时它可以工作” - 谢谢! - OutstandingBill
1个回答

1
你可以使用自己的扩展方法来显式调用适当的扩展方法:

您可以使用自己的扩展方法,显式地调用适当的扩展方法来实现此功能:

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

但是这只有在编译时知道目标框架才能起作用。

1
目前,您可以使用 if (source.Provider is Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider) 作为条件(因为此检查当前包含在所有 EF Core 的 Include / ThenInclude 方法中)。 当然,这是实现特定的,并且可能会发生变化,但现在应该可以工作。 - Ivan Stoev
最终,我决定创建一个IIncludeable<>接口,其中包含EF6实现和EF.Core实现。 - Nick Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接