I'm, using ASP NET Core Identity in order to log in user into his account
But for some reason it started throwing me an Exception
InvalidOperationException: The instance of entity type 'User' cannot be tracked because another instance with the key value '{Id: 99d1aa12-3f75-497d-a4cc-5d2103c1b042}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
What's causing that?
public async Task<IActionResult> Login(string Login, string Password, string ReturnUrl = "/")
{
var user = await _context.Users.AsNoTracking().FirstOrDefaultAsync(x => x.UserName == Login);
if (user == null)
{
return View("Error");
}
var sign = await _signInManager.PasswordSignInAsync(user, Password, true, true); // here
if(!sign.Succeeded)
{
return View("Error");
}
return Redirect(ReturnUrl);
}
You use AsNoTracking here and that's why the issue happend. Remove that and it will work just find.
Also please make sure you know what is AsNoTracking mean before use it.
Cheers