1

I use generic method to update entity data

// In repository implementation
public async Task Update<T>(int id, object model) where T: IEntity // (with Id)
{
   _dbContext.Attach(new T { Id = id }).CurrentValues.SetValues(model);
   await _dbContext.SaveChangesAsync();
}

I found a case in which data is not completely updated. I will give an example.

Simple db entity:

class MyEntity : IEntity
{
   public int Id {get; set;}
   public string Name {get; set;}
   public bool Active {get; set;}
   public Guid EditorGuid {get; set;}
   public DateTime Modified {get; set;}
}

And my simple business logic method:

public async Task ChangeActive(int id, bool active)
{
    var userGuid = _userService.GetCurrent().Guid;

    await _repository.Update<MyEntity>(id, new 
                                           {
                                               EditorGuid = userGuid,
                                               Active = active,
                                               Modified = DateTime.UtcNot
                                           });
}

All queries to the database are logged into the console. When executing the ChangeActive method, I see the following SQL query:

UPDATE public.my_entity 
SET editor_guid = @p0, modified = @p1
WHERE id = @p2;

SQL is generated in such a way that the Active field is not updated. I want to note that in other cases that use the Update method in my code, this problem does not occur.

What could be the problem?

UPDATE

If I explicitly specify a value, then the SQL query is generated correctly

await _repository.Update<MyEntity>(id, new 
{
    EditorGuid = userGuid,
    Active = true, // <-- 
    Modified = DateTime.UtcNot
});
UPDATE public.my_entity 
SET active = @p0, editor_guid = @p1, modified = @p2
WHERE id = @p3;
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dmitriy Gavrilenko
  • 300
  • 1
  • 3
  • 18
  • Are you sure that the parameter `active` is `true` and the field in the DB is `false`? Because if it is the same in both places, it is very possible that EF will avoid adding it to the generated command. – Guilherme Apr 15 '20 at 22:13
  • @Guilherme In the database field Active = true. I am at a loss to set to false. It’s a good assumption that EF does check the updated data with the actual, but it’s not. EF does not execute select query. I have an assumption about default (bool), in cases where I try to set the value to false – Dmitriy Gavrilenko Apr 15 '20 at 22:18

1 Answers1

3

I found the reason in one of the answers on StackOverflow. My problem is no, that I'm trying to set the bool value to false, which is equivalent to default (bool), which EF Core will ignore. Cannot set bool value to false in entity framework update method

Dmitriy Gavrilenko
  • 300
  • 1
  • 3
  • 18