gpt4 book ai didi

entity-framework-core - 在 Entity Framework Core 中检测延迟加载

转载 作者:行者123 更新时间:2023-12-04 12:39:52 24 4
gpt4 key购买 nike

Entity Framework Core 3.1.2 - 我已启用 UseLazyLoadingProxies在我的 DbContext以确保数据完整性,但如果使用,我想在开发过程中抛出异常。

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

最佳答案

我知道的唯一方法是诊断消息。在此处查看示例: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

然后是一个 Hook 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());
}
}

关于entity-framework-core - 在 Entity Framework Core 中检测延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60509189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com