How to Update only single field using EF

2019-01-26 01:44发布

This is the current basic code :

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

I have around 15 fields in Registration table , how ever i just want to update the "Date" field , the object that i receive here is "registration" which only has value for a date , but the current code updates all the entries , what i want is to just update the "Date" field , whose value i have got in "registration"

Help would be much appreciated :)

3条回答
女痞
2楼-- · 2019-01-26 02:18

Try this

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");
        }

Update : as per answer in this 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;
}
查看更多
仙女界的扛把子
3楼-- · 2019-01-26 02:31
Registration registor =db.Registration.First(f=>RegistrationId==RegistrationId);
registor.Date = registration.Date;
db.SaveChanges();

use this for single record updation and i assuming that RegistrationId in your Registration table.

查看更多
Root(大扎)
4楼-- · 2019-01-26 02:37

Attach it to the context in the Unchanged state, and only set Date as modified.

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");
}

You said the incoming entity only has Date filled in, hopefully there's an Id too. :)

查看更多
登录 后发表回答