我使用的是 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; }
}
使用比例尺时,应禁止更新其所有 ScaleLabels,但其 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;
那么什么都不会更新,如果我不使用它,那么所有ScaleLabels 已更新。我想指定 Scale 的 Labels 导航属性的哪些属性被修改,哪些不被修改。
最佳答案
而不是玩IsModified
相关属性(property)CollectionEntry
, 你需要使用 IsModified
PropertyEntry
的属性(property)由 Property
返回Properties
的方法(或 EntityEntry
属性)对于相关集合的每个元素(基本上与您对任何实体的特定属性所做的相同)。
换句话说,而不是
_context.Entry(scale).Collection(c => c.Labels).IsModified = false;
你会使用这样的东西:
foreach (var label in scale.Labels)
foreach (var p in _context.Entry(label).Properties.Where(p => p.Metadata.Name != "Label"))
p.IsModified = false;
关于c# - 如何将 EF Core 相关集合中的属性的 IsModified 设置为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636250/