亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在實體框架和 EF Core 中使用 .Include()

如何在實體框架和 EF Core 中使用 .Include()

C#
喵喔喔 2021-11-28 19:45:18
是否可以以同時適用于 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

    }

}

但這只有在編譯時已知目標框架時才有效。


查看完整回答
反對 回復 2021-11-28
  • 1 回答
  • 0 關注
  • 535 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號