Bel*_*vic 3 c# entity-framework-core asp.net-core asp.net-core-1.1
我正在使用 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; }
}
Run Code Online (Sandbox Code Playgroud)
使用比例尺时,除其 Label 属性外,应禁止更新其所有 ScaleLabels。
[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);
}
Run Code Online (Sandbox Code Playgroud)
如果我使用_context.Entry(scale).Collection(c => c.Labels).IsModified = false;
,则不会更新任何内容,如果我不使用它,则所有 ScaleLabels 都会更新。我想指定比例尺标签导航属性的哪些属性已修改,哪些未修改。
您不需要使用IsModified
相关的属性CollectionEntry
,而是需要使用相关集合的每个元素的方法(或属性)返回IsModified
的属性(基本上与处理任何实体的特定属性相同的方式)。PropertyEntry
Property
Properties
EntityEntry
换句话说,而不是
_context.Entry(scale).Collection(c => c.Labels).IsModified = false;
Run Code Online (Sandbox Code Playgroud)
你会使用这样的东西:
foreach (var label in scale.Labels)
foreach (var p in _context.Entry(label).Properties.Where(p => p.Metadata.Name != "Label"))
p.IsModified = false;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4572 次 |
最近记录: |