entity-framework-core - Blazor Server 组件之间的数据库上下文保持一致

标签 entity-framework-core blazor blazor-server-side lifecycle

我想问一下在组件之间利用数据库上下文的最佳实践是什么? Blazor 服务器、.Net 5、EF Core 5.0.8

情况简介:
组件a, header
组件 b,主要
DbContext 被注册为 Transient,并且 Header 和 Main 都有自己的上下文。

但是在例如:更改 Main 中的数据之后,它不会应用于 Header,因此数据变得不一致。

想法:
1、删除 DbContext 注册并为每个数据库调用手动创建一个新的
2、保留当前架构,但添加额外的调用来刷新数据(需要时)
3、将DbContext注册为Scoped并围绕它构建某种队列服务来逐步处理查询(避免并发调用)并通过EventAggregator消息返回结果。

您怎么看,如何处理这种情况?

最佳答案

根据@Liero的回答,我最初还应用了 IDbContextFactory 来为数据库的每个服务调用创建一个新的上下文实例 - 但是,对于我的应用程序,我需要跨多个组件进行更改跟踪,但我不希望打破工作单元模式,因为这会导致数据库不一致的一些问题。

正如您在步骤(3)中提到的 - 我将 DbContext 保留为范围(据我所知这是默认值),然后我使用 semaphore防止线程问题:

 @code {
        static Semaphore semaphore;
        //code ommitted for brevity
        
         protected override async Task OnInitializedAsync()
         {
             try
             {
                //First open global semaphore
                semaphore = Semaphore.OpenExisting("GlobalSemaphore");

                while (!semaphore.WaitOne(TimeSpan.FromTicks(1)))
                {
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
                //If while loop is exited or skipped, previous service calls are completed.
                ApplicationUsers = await ApplicationUserService.Get();        
             
             }
             finally
             {
                try
                {
                    semaphore.Release();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ex.Message");
                }
            }
        }

这对于我需要跨组件保留更改跟踪的特定用例来说非常有效。 Here's my full answer from another related question.

关于entity-framework-core - Blazor Server 组件之间的数据库上下文保持一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68681120/

相关文章:

.net - 如何从 appsettings 动态设置 Blazor 中授权 View 标记或属性允许的角色或策略?

c# - 如何在 Blazor 服务器应用程序中访问 WCF 服务

c# - Blazor 服务器端是否有任何热重载?

c# - 在 EF Core 中添加一对一关系时迁移数据?

c# - Entityframework Core 无法将类型为 'System.Int32' 的对象转换为类型 'System.Int64'

c# - 如何在 .Net Blazor 中获取 Javascript 回调?

c# - Blazor 客户端和 WCF

linq - Asp.net Core 5.0 Linq Take(1).ElementAt(index)

sql - 存储库模式困境 : Redundant Queries vs. 数据库往返

.net - 不在本地主机上时 SignalR 连接失败