如何在EF Core中相关集合中的属性上将IsModified设置为false? [英] How to set IsModified to false on a property in a related Collection in EF Core?
问题描述
我正在使用Asp.Net Core 1.1,并且有两个类:
I am using Asp.Net Core 1.1 and I have two classes:
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; }
}
使用比例尺时,除其Label属性外,所有其ScaleLabel均应禁止更新.
When a scale is used, all its ScaleLabels should be prohibited to update except for their Label property.
[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均已更新.我想指定缩放"的标签"导航属性的哪些属性被修改,哪些未被修改.
If I use _context.Entry(scale).Collection(c => c.Labels).IsModified = false;
then nothing is updated, and if I don't use it, then all ScaleLabels are updated. I want to specify which properties of the Scale's Labels navigation property are modified and which are not.
推荐答案
您无需使用相关 CollectionEntry
的 IsModified
属性,而需要使用每个实体
属性相关集合的元素(基本上与您对任何实体的特定属性执行的操作相同). EntityEntry
的 Property
方法(或 Properties
属性)返回的 PropertyEntry
的IsModified
Rather than playing with IsModified
property of the related CollectionEntry
, you need to use the IsModified
property of the PropertyEntry
returned by Property
method (or Properties
property) of EntityEntry
for each element of the related collection (basically the same way as you would do for specific property of any entity).
换句话说,代替
_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;
这篇关于如何在EF Core中相关集合中的属性上将IsModified设置为false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!