How to Update only single field using EF

后端 未结 3 1448
傲寒
傲寒 2020-12-18 15:55

This is the current basic code :

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Registration registration)
    {
        if (Mode         


        
3条回答
  •  鱼传尺愫
    2020-12-18 16:30

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

提交回复
热议问题