How to Update only single field using EF

霸气de小男生 提交于 2019-11-29 08:50: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. :)

Nilesh Gajare

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;
}
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!