是否可以以同時適用于 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 }}以上在使用實體框架時工作正常,但.Include()在運行 EF Core 時不起作用(注意using System.Data.Entity);如果 using 語句更改為,using Microsoft.EntityFrameworkCore則它在運行 EF Core 時有效,但在 Entity Framework 中無效。有沒有辦法使框架不可知.Include()?或者至少支持 EF Core 和實體框架?
1 回答

侃侃爾雅
TA貢獻1801條經驗 獲得超16個贊
您可以使用自己的擴展方法來執行此操作,該方法顯式調用適當的擴展方法:
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 回答
- 0 關注
- 535 瀏覽
添加回答
舉報
0/150
提交
取消