How to Update only single field using EF

2019-01-26 01:51发布

问题:

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 :)

回答1:

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. :)



回答2:

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:

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.