本文介绍了在实体框架核心中检测延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Entity Framework Core 3.1.2-我已在我的 DbContext 上启用了 UseLazyLoadingProxies 以确保数据完整性,但是如果要使用它,我想在开发过程中引发异常.

Entity Framework Core 3.1.2 - I have enabled UseLazyLoadingProxies on my DbContext to ensure data integrity, but I want to throw an exception during development if it is used.

每次EF Core延迟加载关系时,如何执行一些代码?

How can I execute some code every time EF Core loads a relationship lazily?

推荐答案

我知道的唯一方法是诊断消息.在此处查看示例: https://www.domstamand.com/getting-feedback-from-entityframework-core-through-diagnostics .

The only way I know is diagnostic messages. See an example here: https://www.domstamand.com/getting-feedback-from-entityframework-core-through-diagnostics.

您想要的事件类是 https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.diagnostics.lazyloading事件数据.

在应用程序的DBContext中

In the application's DBContext

#if DEBUG
    static ApplicationDbContext()
    {
        // In DEBUG mode we throw an InvalidOperationException
        // when the app tries to lazy load data.
        // In production we just let it happen, for data
        // consistency reasons.
        DiagnosticListener.AllListeners.Subscribe(new DbContextDiagnosticObserver());
    }
#endif

然后将一个类挂接到EF通知

Then a class to hook into EF notifications

internal class DbContextDiagnosticObserver : IObserver<DiagnosticListener>
    {
        private readonly DbContextLazyLoadObserver LazyLoadObserver =
            new DbContextLazyLoadObserver();

        public void OnCompleted() { }

        public void OnError(Exception error) { }

        public void OnNext(DiagnosticListener listener)
        {
            if (listener.Name == DbLoggerCategory.Name)
                listener.Subscribe(LazyLoadObserver);
        }
    }

最后是每当延迟加载发生时抛出异常的类

And then finally the class that throws exceptions whenever a lazy load occurrs

internal class DbContextLazyLoadObserver : IObserver<KeyValuePair<string, object>>
    {
        public void OnCompleted() { }
        public void OnError(Exception error) { }

        public void OnNext(KeyValuePair<string, object> @event)
        {
            // If we see some Lazy Loading, it means the developer needs to
            // fix their code!
            if (@event.Key.Contains("LazyLoading"))
                throw new InvalidOperationException(@event.Value.ToString());
        }
    }

这篇关于在实体框架核心中检测延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:30