I have the following piece of code to check if an entry exists in a DBSet and if not, to add it.
As there are some similar entries in the loop, it will try to add the same data more than once, which the linq statement (just after alreadyInserted) should pick up and stop, but for some reason it cannot detect the newly added entries and therefore will add them multiple times.
Any ideas?
foreach (var user in userList.Split(','))
{
var valueFound = false;
var user1 = user;
var defRecord = definitionRecord.Id;
foreach (var valueRecord in this._mps3Context.RefProviderLoginValues.Where(x => user1 == x.UserId))
{
bool alreadyInserted = this._mps3Context.RefProviderLoginValues.Any(
x => x.DefinitionId == defRecord && x.UserId == valueRecord.UserId); // Check we have not already inserted this data
if (alreadyInserted || valueRecord.DefinitionId != definitionRecord.Id)
{
continue;
}
valueFound = true;
break;
}
if (valueFound)
{
continue;
}
//// Since the there's no existing record, create it
var newLoginValueRecord = new RefProviderLoginValues
{
CreatedById = this._currentUser.UserId,
CreatedDate = DateTime.Now,
ModifiedById = this._currentUser.UserId,
ModifiedDate = DateTime.Now,
UserId = user1,
DefinitionId = definitionRecord.Id,
Value = this.CheckEncryptionRequired(definitionRecord.Default, refLoginDefinition.Encrypted ?? false)
};
this.RefProviderLoginValues.Add(newLoginValueRecord); // Add entity to context
}