【问题标题】:How to set IsModified to false on a property in a related Collection in EF Core?如何在 EF Core 的相关集合中的属性上将 IsModified 设置为 false?
【发布时间】:2023-03-08 21:33:02
【问题描述】:

我使用的是 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; }
}

使用比例尺时,应禁止更新其所有 ScaleLabel,但其 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 =&gt; c.Labels).IsModified = false;,则不会更新任何内容,如果我不使用它,则会更新所有 ScaleLabel。我想指定 Scale 的 Labels 导航属性的哪些属性被修改,哪些没有。

【问题讨论】:

    标签: c# asp.net-core entity-framework-core asp.net-core-1.1


    【解决方案1】:

    与其玩相关CollectionEntryIsModified属性,不如使用EntityEntryProperty方法返回的PropertyEntryIsModified属性(或Properties属性)用于相关集合的每个元素(基本上与处理任何实体的特定属性的方式相同)。

    换句话说,而不是

    _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;
    

    【讨论】:

    • 谢谢,这正是我想要的。我还需要使用更新而不是附加并仅为修改后的实体添加条件,以便可以添加新实体。
    猜你喜欢
    • 2020-07-04
    • 2018-07-05
    • 1970-01-01
    • 2023-02-03
    • 2018-11-10
    • 2021-09-03
    • 2014-10-04
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多