场景:
我目前正在创建一个基本的服务器端Blazor
crud应用程序,Blazor
是我刚刚开始尝试的东西。
从编辑页面导航回索引页面时,我遇到了后退按钮的问题。问题如下:
- 我编辑了一条记录,并在不保存的情况下对字段进行了一些更改
- 我单击返回按钮,该按钮可导航回索引页
- 我在记录列表中更改的记录显示了我在编辑表单中所做的更改,但我没有点击保存
- 我刷新页面,记录会返回到原始状态
我尝试过使用一个点击按钮和以下内容:
<a href="/branches" class="btn btn-sm btn-secondary mr-2"><i class="oi oi-arrow-circle-left"></i> Back</a>
问题:
你知道我哪里错了吗?
索引:
@page "/branches"
@inject BranchRepository repository
<GenericList List="branches">
<WholeListTemplate>
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in branches)
{
<tr>
<td>@item.sName</td>
<td>@item.sBranchNumber</td>
<td><a href="/branch/edit/@item.Id" class="btn btn-sm btn-warning">Edit</a></td>
</tr>
}
</tbody>
</table>
</WholeListTemplate>
</GenericList>
@code {
List<Core.Entities.Branch> branches;
protected async override Task OnInitializedAsync()
{
branches = null;
branches = await repository.GetAllBranches();
}
}
编辑:
@page "/branch/edit/{id:int}"
@inject NavigationManager navigationManager
@inject BranchRepository repository
<h2>Edit Branch</h2>
<hr />
@if(branch != null)
{
<BranchEditForm Branch="branch" OnValidSubmit="Update" />
}
@code {
[Parameter] public int Id { get; set; }
private Branch branch;
protected override void OnInitialized()
{
branch = repository.GetById(Id);
}
private void Update()
{
repository.Update(branch);
navigationManager.NavigateTo("branches");
}
}
BranchEditForm:
<EditForm Model="Branch" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator />
<div class="form-row">
<div class="form-group col-md-6">
<label>
Name
</label>
<InputText class="form-control" @bind-Value="@Branch.sName" />
<ValidationMessage For="@(() => Branch.sName)" />
</div>
<div class="form-group col-md-6">
<label>
Branch Number
</label>
<InputText class="form-control" @bind-Value="@Branch.sBranchNumber" />
<ValidationMessage For="@(() => Branch.sBranchNumber)" />
</div>
</div>
<a href="/branches" class="btn btn-sm btn-secondary mr-2"><i class="oi oi-arrow-circle-left"></i> Back</a>
<button type="submit" class="btn btn-sm btn-success"><i class="oi oi-document"></i> Save</button>
</EditForm>
@code {
[Parameter] public Branch Branch { get; set; }
[Parameter] public EventCallback OnValidSubmit { get; set; }
}
原因
DbContext缓存了对实体所做的更改
解决方案
通过有用的评论,我研究了EF Core中的DbContext缓存,发现了一篇有用的帖子https://codethug.com/2016/02/19/Entity-Framework-Cache-Busting/.
通过这个,我找到了一种重新加载实体或实体集合的方法:
一个实体
public async Task ReloadEntity<TEntity>(TEntity entity)
{
if (entity != null) await context.Entry(entity).ReloadAsync();
return;
}
多个实体
注意-根据上面链接的帖子,这是少数实体的理想选择。如果在中传递大列表,可能会出现性能问题
public async Task ReloadEntities<TEntity>(List<TEntity> entities)
{
if (entities.Count() > 0)
{
foreach (var entity in entities) if (entity != null) await context.Entry(entity).ReloadAsync();
}
return;
}