Hello I am trying to insert data in table as below
var newClientUsers = new List<Entities.ClientUser>();
var existingClientUsers = await mycontext.ClientUser.AsNoTracking().ToArrayAsync(cancellationToken: cancellationToken);
var clientUserList = clientUsers.Select(s =>
new Entities.ClientUser
{
UserName = s.UserName,
OrganizationId = s.OrganizationId
}).ToList();
newClientUsers = clientUserList.Except(existingClientUsers, new ClientUserComparer()).ToList();
if (newClientUsers.Count > 0)
{
await mycontext.ClientUser.AddRange(newClientUsers);
await mycontext.SaveChangesAsync();
}
else
{
_logger.LogInformation($"{DateTime.UtcNow} NoClientUsersAdded");
}
This method fails to add data and gives error
System.InvalidOperationException: The instance of entity type ‘ClientUser’ cannot be tracked because another instance with the same key value for is already being tracked.
However i do not get issue when I remove AsNoTracking() from query or use AddRangeAsync. I want to understand what is the correct scenario for using AsNotracking for inserting data.
if you have any reference please share.