C# 更新验证失败后,使用.Include(相关实体)重新显示原始模型
当用户发送GET请求以编辑记录时,我正在加载通过相关实体发送到视图的模型。包括如下内容:C# 更新验证失败后,使用.Include(相关实体)重新显示原始模型,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,当用户发送GET请求以编辑记录时,我正在加载通过相关实体发送到视图的模型。包括如下内容: var client = await _context.Client .Include(c => c.Office) .Where(c => c.client_id == id) .AsNoTracking()
var client = await _context.Client
.Include(c => c.Office)
.Where(c => c.client_id == id)
.AsNoTracking()
.SingleOrDefaultAsync();
return View(client);
当用户发回编辑表单和必填字段缺少ModelState.IsValid==false时,将不执行更新,并将包含未保存更改的模型发送回视图
public async Task<IActionResult> Edit(Client client_edited )
{
if (!ModelState.IsValid)
{
return View(client_edited); // .Include(c => c.Office) is missing
}
}
回答我自己的问题以防对别人有帮助 基于see EF复制当前值,我能够通过几行代码解决问题,示例如下:
public async Task<IActionResult> Edit(Client client_posted)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", "Record is missing required values");
// requery the client entity from our db to get related child entities
var client_current = await _context.Client
.Include(c => c.Office)
// include 4 or 5 more entities here
.Where(c => c.client_id == client_posted.client_id)
.AsNoTracking()
.SingleOrDefaultAsync();
// now replace client_current values with client_posted values by
// 1 - add entity to your db context (we are not saving it)
_myDbContext.Client.Add(client_posted);
// 2 - use the db context to extract current values from the client entity posted
var client_posted_values =_myDbContext.Entry(client_posted).CurrentValues;
// 3 - copy the extracted values to the client_current we re-queried from db
_myDbContext.Entry(client_current).CurrentValues.SetValues(client_posted_values);
// 4 return the view passing client with original values and the attached office entity(ies)
return View(client_current);
}
// otherwise ModelState is valid, do the update here
...
...
}
public async Task<IActionResult> Edit(Client client_posted)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", "Record is missing required values");
// requery the client entity from our db to get related child entities
var client_current = await _context.Client
.Include(c => c.Office)
// include 4 or 5 more entities here
.Where(c => c.client_id == client_posted.client_id)
.AsNoTracking()
.SingleOrDefaultAsync();
// now replace client_current values with client_posted values by
// 1 - add entity to your db context (we are not saving it)
_myDbContext.Client.Add(client_posted);
// 2 - use the db context to extract current values from the client entity posted
var client_posted_values =_myDbContext.Entry(client_posted).CurrentValues;
// 3 - copy the extracted values to the client_current we re-queried from db
_myDbContext.Entry(client_current).CurrentValues.SetValues(client_posted_values);
// 4 return the view passing client with original values and the attached office entity(ies)
return View(client_current);
}
// otherwise ModelState is valid, do the update here
...
...
}