简体   繁体   中英

EF Repository with UoW Update

I believe this is asked somewhere else but I can't find straight solution. My Api is passing object model and on the server side every value of that object which is not passed is considered null (makes sense). Is there way I can tell EF6 not to update entity with null values from passed object in manner I don't have to write each property and check if it's null.

Pseudo code

API

Update(int id, TaskEntity obj)
{
    unitOfWork.Tasks.Update(id, userTask);
    ...
    unitOfWork.Save()
}

Repo update

Update(int id, T entity)
        {
            var existingRecord = Get(id); //Gets entity from db based on passed id
            if (existingRecord != null)
            {
                var attachedEntry = Context.Entry(existingRecord);
                attachedEntry.CurrentValues.SetValues(entity);
            }
        }

My problem is that any data with null values will actually rewrite existing db record value with nulls.

Please point me to a solution or article where this is solved. Should I go reflections, maybe automapper could handle this (it's not its purpose i believe), or some kind of helper method should be written, as my objects can contain sub object.

Thank you in advance.

You can do something like this

Update(int id, T entity,string[] excludedFields)
{
    var existingRecord = Get(id); //Gets entity from db based on passed id
     if (existingRecord != null)
     {
          var attachedEntry = Context.Entry(existingRecord);
          attachedEntry.CurrentValues.SetValues(entity);
          for(var field in excludedFields)
          {
               attachedEntry.Property(field).IsModified = false;
          }
     }
}

some scenaries requires you to update part of the object and sometimes other parts, the best way in my opinion is to pass the fields to exclude from the update

hope it will help you

Personally not a big fan of hitting database and doing a get operation before doing an update. May be while doing the ajax call, you can send a list of properties which you should update (so that the scenario where updating to null values (erasing existing ones) will also be handled).

I'm doing small modifications to what @Hadi Hassan has done (without hitting database for getting the entity):

Update(T entity,string[] includedFields)
{
    var existingRecord = Context.Attach(entity); // assuming primary key (id) will be there in this entity
    var attachedEntry = Context.Entry(existingRecord);

    for(var field in includedFields)
    {
       attachedEntry.Property(field).IsModified = true;
    }

}

Note - attachedEntry.Property(field).IsModified will not work for related entities

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM