检测实体框架核心中的延迟加载

问题描述 投票:0回答:1

Entity Framework Core 3.1.2-我已在UseLazyLoadingProxies上启用DbContext以确保数据完整性,但如果要使用它,我想在开发期间抛出异常。

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

entity-framework-core lazy-loading
1个回答
1
投票

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

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

在应用程序的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通知的类

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

然后是最后一个在发生延迟加载时引发异常的类

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());
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.