【问题标题】:How to Update only single field using EF如何使用 EF 仅更新单个字段
【发布时间】:2014-04-30 05:35:52
【问题描述】:

这是当前的基本代码:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Registration registration)
    {
        if (ModelState.IsValid)
        {
            db.Entry(registration).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(registration);
    }

我在注册表中有大约 15 个字段,但我只想更新“日期”字段,我在这里收到的对象是“注册”,它只有一个日期的值,但当前代码更新了所有条目,我想要的只是更新“日期”字段,我在“注册”中获得了它的值

非常感谢您的帮助:)

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework entity-framework-5


    【解决方案1】:

    将其附加到Unchanged 状态的上下文中,并且仅将Date 设置为已修改。

    if (ModelState.IsValid)
    {
        db.Registrations.Attach(registration); // attach in the Unchanged state
        db.Entry(registration).Property(r => r.Date).IsModified = true;
        // Date field is set to Modified (entity is now Modified as well)
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    

    你说传入的实体只填写了Date,希望也有一个ID。 :)

    【讨论】:

    • 是的,有一个 id ,是 .Attach EF 附带的方法吗?还是必须制作?因为 db.Attach(注册);给出错误说需要创建此方法
    • 抱歉,Attach() 方法在 DbSet 本身上。已更正。
    • 感谢一堆 :) 任务完成 :)
    【解决方案2】:

    试试这个

    if (ModelState.IsValid)
            {
                db.Entry(registration).State = EntityState.Modified;
                db.Entry(registration).Property(x => x.Name).IsModified = false; //Add fields which you don't want to modify
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    

    更新:根据post中的答案

    var excluded = new[] { "property1", "property2" };
    var entry = context.Entry(obj);
    entry.State = EntityState.Modified;
    foreach (var name in excluded)
    {
        entry.Property(name).IsModified = false;
    }
    

    【讨论】:

    • 据此我将不得不手动排除一些记录,比如大约 14 条,我不能只提一个我必须更新的属性吗?如下所示: UPDATE dbo.registrations SET Date = registration WHERE id = registrations.id -- 我不关心其他字段
    【解决方案3】:
    Registration registor =db.Registration.First(f=>RegistrationId==RegistrationId);
    registor.Date = registration.Date;
    db.SaveChanges();
    

    将其用于单个记录更新,我假设 RegistrationId 在您的注册表中。

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 2022-12-17
      • 2014-01-27
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      相关资源
      最近更新 更多