0

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
}
Weetobix
  • 55
  • 1
  • 11
  • Have you tried debugging? If so, is it skipping the inner `foreach loop`? If so, what's the value of user1 and x.UserId? – sr28 May 18 '16 at 16:14
  • Your code seems confusing. Why do you need to loop through the collection? If you have defRecord and user1 can't you just search to see if it's there and if not just insert it? You problem is due to you not call SaveChanges so the context is not "aware" of the newly inserted entity. – jpgrassi May 18 '16 at 16:41
  • Also, shouldn't this line: this.RefProviderLoginValues.Add be: this._mps3Context.RefProviderLoginValues.Add ? – jpgrassi May 18 '16 at 16:53

0 Answers0