How to Update only single field using EF

后端 未结 3 1438
傲寒
傲寒 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:13
    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.

    0 讨论(0)
  • 2020-12-18 16:19

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

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题