c# - 如何将 EF Core 相关集合中的属性的 IsModified 设置为 false?

标签 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<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,但其 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 => c.Labels).IsModified = false; 那么什么都不会更新,如果我不使用它,那么所有ScaleLabels 已更新。我想指定 Scale 的 Labels 导航属性的哪些属性被修改,哪些不被修改。

最佳答案

而不是玩IsModified相关属性(property)CollectionEntry , 你需要使用 IsModified PropertyEntry 的属性(property)由 Property 返回Properties 的方法(或 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;

关于c# - 如何将 EF Core 相关集合中的属性的 IsModified 设置为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636250/

相关文章:

.net-core - 如何通过 NLog 记录 Entity Framework Core 操作

asp.net-mvc - EF Core 中的 SQL Server 排序规则

entity-framework-core - 尝试在 EFCore Spanner 提供程序上添加对索引使用的支持

c# - ASP.NET Core 托管在 Windows 服务中 - 未提供静态文件(即/wwwroot 的内容)

asp.net-mvc - 我可以将本地数据库与 Stormpath 一起使用吗?

C#:委托(delegate),紧凑访问者, "universal callable"参数类型

c# - 为单元测试准备编码的最佳策略

c# - 如何在没有数据库的情况下为开发环境实现 SignInManager?

c# - 如何将实体从一个 Entity Framework 上下文复制到另一个 Entity Framework 上下文?

c# - WPF ContextMenu 单击时消失