0

Problem is Table Columns are getting updated with NULL if i dont defined them in my controller.Below is my Controller Action.

  [HttpPost]
  public ActionResult GetEditRecord(UserDetail MU, string actiontype)
    {
        if (actiontype == "Save")
        {
            UserDetail Ud = new UserDetail();
            _unitOfWork = new GenericUnitOfWork();
            Ud.ID = MU.ID;
            Ud.FirstName = MU.FirstName;
            Ud.LastName = MU.LastName;
            Ud.IsDeleted = false;
            Ud.FkCompanyId = 5;
            Ud.FkRegionId = 1;
            _unitOfWork.GetRepoInstance<UserDetail>().update(Ud);
            _unitOfWork.SaveChanges();
        }
        return RedirectToAction("ManageUsers"); ;
    }

I Have 10 columns in UserDetails but i need to edit only 6 columns but when i click on update the other fields are getting save as NULL. Below is My GeneralRepository code to update Entity

 public void update(TEntity entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;        

    }

Please tell if i am missing something.

Steve
  • 352
  • 2
  • 6
  • 24
  • You're creating a new item then saving them `Ud = new UserDetail();`, tihs will overwrite all existing data. If you don't want this you need to read the data out the db, update it, then save it back. – Liam Mar 24 '16 at 11:00
  • I have edit option in my page and after clicking on that i have to show 6 columns only but in table i have 10 columns.Please let me know which code i need to share as i am not getting the thing you saying about read the data. – Steve Mar 24 '16 at 11:06
  • What ORM are you using? Entity Framework? – Liam Mar 24 '16 at 11:12
  • Possible duplicate of [Updating records using a Repository Pattern with Entity Framework 6](http://stackoverflow.com/questions/30066247/updating-records-using-a-repository-pattern-with-entity-framework-6) – Liam Mar 24 '16 at 11:12
  • code first approach... – Steve Mar 24 '16 at 11:13

1 Answers1

1

Well, that is reasonable, you are basically creating new record and your default values are NULL.

You should probably want to first locate your record (FindById or something) and then update it.

Unrelated: Shouldn't unit of work be disposable?

vbilopav
  • 156
  • 9
  • yes it is implementing the IDisposable class already. and i am retrieving the data by Edit option then Update button come. – Steve Mar 24 '16 at 11:08
  • @Steve if you don't call `Dispose()`, it doesn't matter that the class implements IDisposable. The object will stay around, probably holding open transactions and connections, until the GC collects it – Panagiotis Kanavos Mar 24 '16 at 11:27