brad
brad

Reputation: 1445

Update Entity Not Being Tracked By Entity Framework

I am building an API with .NET Core 2.0 and Entity Framework Core.

I have a database of users. When the login URI is called, I find the user in the database like so:

User user = _usersRepository.GetUserByEmail(model.Email); 

I then create a token (Guid) that is stored in a dictionary alongside the user object that I just fetched. The token is returned to the consumer and is then required for authorization.

For controller actions that require authorization, a custom attribute fetches the current user object from the dictionary (using their token) and passes it to the controller using HttpContext.Items.

I now have the currently logged in User object inside the controller.

Inside the controller, I would like to alter a property of this user object and then update the database entry for that user.

This is what I would like to be able to do (simplified):

User authenticatedUser = HttpContext.Items.TryGetValue("authenticatedUser" ...)
authenticatedUser.Username = "John Doe";  
_usersRepository.SaveChanges(); 

The following works, but introduces an extra database query, which seems pointless and inefficient seeing as I have the user object right there as authenticatedUser:

User authenticatedUser = HttpContext.Items.TryGetValue("authenticatedUser" ...)   
User user = _usersRepository.GetUserById(authenticatedUser.Id);  
user.Username = "John Doe";  
_usersRepository.SaveChanges();  

How can I save the changes made to authenticatedUser without having to fetch from my database again?

Upvotes: 0

Views: 600

Answers (1)

progrAmmar
progrAmmar

Reputation: 2670

I think what you are looking for is Attach

User authenticatedUser = HttpContext.Items.TryGetValue("authenticatedUser" ...)   
if(authenticatedUser != null)
{
    _usersRepository.Attach(authenticatedUser);  
    authenticatedUser.Username = "John Doe";  
    _usersRepository.SaveChanges(); 
}

Upvotes: 3

Related Questions