Linq查询DBSet没有获取新添加的条目

时间:2016-05-18 16:00:30

标签: c# linq ienumerable dbset

我有以下代码来检查DBSet中是否存在条目,如果不存在,则添加它。

由于循环中有一些类似的条目,它会尝试多次添加相同的数据,linq语句(刚刚插入之后)应该拾取和停止,但由于某种原因它无法检测到新添加的条目,因此将多次添加。

有什么想法吗?

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
}

0 个答案:

没有答案