CombineDeletedEntities / SeparateDeletedEntities添加重复实体

时间:2014-09-10 20:35:58

标签: c# invalidoperationexception entityspaces

我有一个网格,数据源设置为EntitySpaces集合,带有复选框列。选中该复选框后,我想创建一个记录,当它被清除时,我想删除相同的记录。

为避免明显的PK违规保存,如果用户反复检查并取消选中某个项目,我会尝试检索以前删除的实体并将其标记为未删除。但是,当我在集合上使用CombineDeletedEntitiesSeparateDeletedEntities时,它会在集合中创建重复的条目。

roleFunctions.CombineDeletedEntities();

// On third cycle through, this is the error line
RoleFunction foundItem = roleFunctions.FindByPrimaryKey(roleName, functionName);

if (foundItem != null) 
{
    foundItem.RowState = esDataRowState.Unchanged;

    // Extraneous logic...
}
else
{
    // Create new item...
}

roleFunctions.SeparateDeletedEntities();

所以基本上当我第三次FindByPrimaryKey时,EntitySpaces以某种方式创建了一个额外的项目,导致InvalidOperationException的消息为Sequence contains more than one matching element

之前是否有人使用EntitySpaces进行此操作,您是如何在单个会话中多次处理用户多次创建和删除同一实体的?

1 个答案:

答案 0 :(得分:0)

这是一个相当容易的修复,特别是因为EntitySpaces是开源的。我用来避免创建重复记录的两种方法如下所示:

public override void CombineDeletedEntities()
{
    if (this.deletedEntities != null && this.deletedEntities.Count > 0)
    {
        foreach (T entity in deletedEntities)
        {
            entities.Add(entity);
        }
    }
}

public override void SeparateDeletedEntities()
{
    foreach (T entity in this.entities)
    {
        if (entity.rowState == esDataRowState.Deleted)
        {
            if (deletedEntities == null)
            {
                deletedEntities = new BindingList<T>();
            }

            deletedEntities.Add(entity);
        }
    }

    if (this.deletedEntities != null && this.deletedEntities.Count > 0)
    {
        foreach (T entity in deletedEntities)
        {
            entities.Remove(entity);
        }
    }
}

考虑到上述情况,每当我们调用deletedEntities时,代码将继续将相同的实体添加回SeparateDeletedEntities列表。

简单的解决方案是在与正确的集合结合时清除deletedEntities集合:

public override void CombineDeletedEntities()
{
    if (this.deletedEntities != null && this.deletedEntities.Count > 0)
    {
        foreach (T entity in deletedEntities)
        {
            entities.Add(entity);
        }

        this.deletedEntities.Clear();
    }
}

这个快速而肮脏的修复方法的缺点是,在调用collection.Save()之后,您可能不希望在调用CombineDeletedEntities之前致电SeparateDeletedEntities,因为您有一个空deletedEntities收集可能会导致您的保存跳过所有删除。

我本来希望在if (!deletedEntities.Contains(entity))例程中添加SeparateDeletedEntities调用,但是相等比较会将实体视为不同,所以我选择了更简单的解决方案。