【发布时间】:2023-03-08 21:33:02
【问题描述】:
我使用的是 Asp.Net Core 1.1,我有两个类:
public class Scale
{
[Key]
public int ScaleId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal DefaultValue { get; set; }
public List<ScaleLabel> Labels { get; set; }
}
public class ScaleLabel
{
[Key]
public int ScaleLabelId { get; set; }
public int ScaleId { get; set; }
public virtual Scale Scale { get; set; }
public decimal Value { get; set; }
public string Label { get; set; }
}
使用比例尺时,应禁止更新其所有 ScaleLabel,但其 Label 属性除外。
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ScaleId,Name,Description,DefaultValue,Labels")] Scale scale)
{
if (id != scale.ScaleId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
if (IsScaleUsed(id))
{
_context.Scales.Attach(scale);
_context.Entry(scale).Collection(c => c.Labels).IsModified = false;
}
else
{
_context.Update(scale);
}
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ScaleExists(scale.ScaleId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(scale);
}
如果我使用_context.Entry(scale).Collection(c => c.Labels).IsModified = false;,则不会更新任何内容,如果我不使用它,则会更新所有 ScaleLabel。我想指定 Scale 的 Labels 导航属性的哪些属性被修改,哪些没有。
【问题讨论】:
标签: c# asp.net-core entity-framework-core asp.net-core-1.1