1

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

ZaraQ
  • 57
  • 1
  • 12

3 Answers3

6

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

Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
1

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;
}
Community
  • 1
  • 1
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73
  • according to this i'll have to manually exclude a number of records , like around 14 , cant i just mention one property that i have to update? something like below : UPDATE dbo.registrations SET Date = registration WHERE id = registrations.id -- i don't care about the other fields – ZaraQ Apr 30 '14 at 05:47
1
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.

Shahzad Khan
  • 432
  • 2
  • 14