EF 6 ChangeTracker消除重复的实体条目

时间:2016-12-09 23:32:23

标签: entity-framework

我遇到了一个场景,在某些情况下,DbContext ChangeTracker可能有两个相同的条目,都标记为“已添加”状态。

我整理了一个FixState()辅助方法,该方法跟踪即将添加/更新的实体等。在此FixState()中是否有办法告诉更改跟踪器不再跟踪重复的对象?

我使用的entry.State = EntityState.Unchanged;似乎不起作用:

public void FixState()
{
    var changeTrackedEntities = ChangeTracker.Entries<IObjectWithState>();
    // In place list used to ensure the same entities don't get marked as added twice
    var list = new List<Int64>();

    foreach (var entry in changeTrackedEntities) {
        IObjectWithState stateInfo = entry.Entity;
        if (entry.Entity is INWatchEntityObject)
        {
            unchecked
            {
                Int64 sixtyFourBitValue 
                    = ((INWatchEntityObject)entry.Entity).Id | ((entry.Entity.GetType().GetHashCode()) << 32);

                if (!list.Contains(sixtyFourBitValue)) {
                    list.Add(sixtyFourBitValue);
                    entry.State = Utilities.ConvertState(stateInfo.State);
                }
                else {
                    // Duplicate object found, mark it as Unchanged.
                    entry.State = EntityState.Unchanged;
                }
            }
        }
    }
}

0 个答案:

没有答案