如何解决使用Blazor服务器从Entity Framework流结果
因此,我尝试了许多事情,但到目前为止,我没有尝试做任何想要的事情。我希望该页面应加载一个空表,然后在加载数据时每半秒出现一条记录。但是,这不会发生。该应用程序挂起,因为首先获取所有数据,然后立即全部显示。到目前为止,这是我收集的内容:
- 一则帖子提到,要正确流式传输,您必须检测预渲染并在预渲染之后开始请求数据。
- 另一篇文章提到只要关闭跟踪功能,Entity Framework核心就会自动传输结果。
所以我通过以下方式将此Pre-Render Flag Component用作级联值:
App.Razor
<PreRenderCascade>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry,there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</PreRenderCascade>
ViewManagerService.cs
namespace ViewManager.Services
{
public interface IViewManagerService
{
IAsyncEnumerable<Rule> GetRules();
}
public class ViewManagerService : IViewManagerService
{
private readonly IViewManagerContext _dbContext;
public ViewManagerService(IViewManagerContext dbContext)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}
public async IAsyncEnumerable<Rule> GetRules()
{
foreach (var rule in _dbContext.Rules.AsNoTracking())
{
Thread.Sleep(500);
yield return rule;
}
}
}
}
睡眠在那里,因为否则我无法确定数据是流传输还是一次全部获取。
FetchData.razor
@page "/fetchdata"
@using ViewManager.Models
@using ViewManager.Services
@inject IViewManagerService _viewManager
<h1>Rules Table</h1>
@if (_rules == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Object Id</th>
<th>Rule Name</th>
<th>Context Code</th>
<th>Enforced</th>
</tr>
</thead>
<tbody>
@foreach (var rule in _rules)
{
<tr>
<td>@rule.RuleId</td>
<td>@rule.ObjectId</td>
<td>@rule.RuleName</td>
<td>@rule.ContextCode</td>
<td>@rule.EnforceIndicator</td>
</tr>
}
</tbody>
</table>
}
@code {
private readonly List<Rule> _rules = new List<Rule>();
[CascadingParameter(Name = "PreRendering")]
protected bool IsPreRendering { get; set; }
protected override async Task OnInitializedAsync()
{
if (IsPreRendering)
{
return;
}
await foreach (var rule in _viewManager.GetRules())
{
_rules.Add(rule);
StateHasChanged();
}
}
}
我认为我追求的应该是可行的,我想念的是什么?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。