1
我使用Asp.Net 1.1的核心和我有兩個類:如何在EF Core的相關集合中的屬性上將IsModified設置爲false?
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應禁止除了他們的標籤屬性進行更新。
[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被更新。我想指定縮放標籤導航屬性的哪些屬性被修改,哪些不屬於。
謝謝,這是我一直在尋找。我還需要使用update而不是attach,併爲只有修改的實體添加條件,以便可以添加新的條件。 –