.net core EF 开启延迟查询 后使用 AsNoTracking 报错问题解决 同时 添加 ef 打印sql

 

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning': An attempt was made to lazy-load navigation 'OrderItems' on a detached entity of type 'OrderProxy'. Lazy-loading is not supported for detached entities or entities that are loaded with 'AsNoTracking'. This exception can be suppressed or logged by passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

 上图 报错的事件ID

event ID 'CoreEventId.DetachedLazyLoadingWarning' 

执行请求时发生了未经处理的异常。

System.InvalidOperationException:为警告“Microsoft.EntityFrameworkCore.Infrastructure.DisconnectedLazyLoadingWarning”生成错误:试图在类型为“OrderProxy”的分离实体上延迟加载导航“OrderItems”。分离的实体或使用“AsNoTracking”加载的实体不支持延迟加载。通过将事件ID“CoreEventId.DisconnectedLazyLoadingWarning”传递到“DbContext.OnConfiguring”或“AddDbContext”中的“ConfigureWarnings”方法,可以抑制或记录此异常。

原因 ef core 默认不支持 延迟加载

下面 解决 上述问题

开启延迟加载需要nuget下载

Microsoft.EntityFrameworkCore.Proxies

        services.AddDbContext<ShopDBContext>(options =>
            {
                string con = Configuration.GetConnectionString("con");
                options.UseLazyLoadingProxies()//开启延迟加载 默认是开启的 true
                .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.DetachedLazyLoadingWarning)) //忽略AsNoTracking 报错
                .UseMySql(con, MySqlServerVersion.AutoDetect(con))
                .UseLoggerFactory(LoggerFactory.Create(options =>
                {
                    options.AddConsole();//开启ef打印sql语句
                }));
            });

 

posted on 2023-06-01 08:45  是水饺不是水饺  阅读(766)  评论(0)    收藏  举报

导航