C# 如何将EF Core中相关集合中的属性IsModified设置为false?
我正在使用Asp.Net Core 1.1,我有两个类:C# 如何将EF Core中相关集合中的属性IsModified设置为false?,c#,asp.net-core,entity-framework-core,asp.net-core-1.1,C#,Asp.net Core,Entity Framework 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<Sca
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; }
}
公共班级规模
{
[关键]
公共int ScaleId{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共十进制默认值{get;set;}
公共列表标签{get;set;}
}
公共类ScaleLabel
{
[关键]
公共int ScaleLabelId{get;set;}
公共int ScaleId{get;set;}
公共虚拟比例{get;set;}
公共十进制值{get;set;}
公共字符串标签{get;set;}
}
使用比例时,应禁止更新其所有比例标签,但标签属性除外
[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);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务编辑(int-id,[Bind(“ScaleId,Name,Description,DefaultValue,Labels”)]Scale
{
if(id!=scale.ScaleId)
{
返回NotFound();
}
if(ModelState.IsValid)
{
尝试
{
如果(已使用(id))
{
_上下文。缩放。附加(缩放);
_context.Entry(scale).Collection(c=>c.Labels).IsModified=false;
}
其他的
{
_更新(规模);
}
wait_context.SaveChangesAsync();
}
catch(DbUpdateConcurrencyException)
{
如果(!ScaleExists(scale.ScaleId))
{
返回NotFound();
}
其他的
{
投掷;
}
}
返回操作(“索引”);
}
返回视图(比例);
}
如果我使用
\u context.Entry(scale).Collection(c=>c.Labels).IsModified=false代码>然后什么都不更新,如果我不使用它,那么所有的ScaleLabel都会更新。我想指定磅秤标签导航属性的哪些属性已修改,哪些未修改。您需要使用property
方法返回的PropertyEntry
的IsModified
属性,而不是使用相关CollectionEntry
的IsModified
属性(或Properties
property)的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;
谢谢,这就是我一直在寻找的。我还需要使用更新,而不是附加和添加条件,只有修改后的实体,以便可以添加新的实体。