Reputation: 13
var user = _context.Users.Single(u => u.Id == userId);
user.AssignedInfo = _mapper.Map<AssignedInfo>(assignedInfoDTO);
_context.SaveChanges();
In this case with EF, after the query with the method Single
, all other properties but AssignedInfo
on the user entity will be overwritten? or are skipped and only the AssignedInfo
property is updated?
I ask this because there's a big chance some other users may update those other columns of the table from other endpoints in the api, so I don't want to overwrite other properties than AssignedInfo
on this particular endpoint.
Does it work that way or it does update the entire row with all the fields obtained in the query? I just need to update that particular property, and that's the only point where that property is being updated.
Upvotes: 0
Views: 283
Reputation: 1444
When you use Single
method, EF Core starts to track the selected row, which is user
with userId
that is intended. Then after changes in user properties, when you use SaveChanges()
, EF Core intelligently generates a query which only updates the fields that has been changed, which in your case is AssignedInfo
. So the generated query will be something like :
UPDATE [Users] SET [AssignedInfo ] = @p0
WHERE [Id] = @p1;
This is a parameterized query (to prevent from SQL injection) so :
@p0 = _mapper.Map<AssignedInfo>(assignedInfoDTO)
and
@p1 = userId
By the way, you can see the EF Core generated queries just by adding
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
to LogLevel
property of Logging
property of appsettings.Development.json
, so in development mode the queries are shown in the command window or vs output window.
Upvotes: 1