【问题标题】:Update record in TableServiceContext by a new instance of the record object?通过记录对象的新实例更新 TableServiceContext 中的记录?
【发布时间】:2012-03-07 14:10:16
【问题描述】:

我有一个 azure 表记录对象定义为

[DataServiceKey("PartitionKey", "RowKey")]
public class TableRecord
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTime Timestamp { get; set; }
    public string Data { get; set; }
}

记录用作存储库基础架构的一部分,它接受业务逻辑级别的数据对象并将其序列化为 Data 属性,然后将代码保存到表存储中,并在返回客户端之前将其反序列化,因此业务逻辑对记录以及 PartitionKey 和 RowKey 一无所知。

这里是存储库方法

public TEntity RegisterSave<TEntity>(TEntity entity, bool createNew)
{
    var storeRec = _strategy.GetStoreRecord(entity);
    if (createNew)
        _context.AddObject(storeRec.TableName, storeRec.Record);
    else
    {
        try
        {
            _context.AttachTo(storeRec.TableName, storeRec.Record, "*");                    
        }
        catch (InvalidOperationException)
        {
            // AttachTo can throw an exception if the entity is already being tracked.
            // Ignore
        }

        _context.UpdateObject(storeRec.Record);
    }
    return entity;
}

_strategy 负责将实体类型正确映射到表名,以及使用键正确创建 TableRecord 并将实体序列化到记录中。 storeRec.Record 属性是 TableRecord 类的实例。这种方法适用于创建新记录和阅读记录。

但是当我尝试使用新数据更新现有记录时,更新失败并抱怨它无法更新上下文未跟踪的实体。尽管如果在调试器中单步执行代码,事实证明实际上发生了两个异常 - 首先在 AttachTo 方法中抱怨正在跟踪具有相同键的实体,然后立即在 UpdateObject 抱怨关于它不是。

我哪里做错了?

知道了

好的,在 ilspy 的帮助下,我找到了问题的根本原因。 DataServiceContext 为加载到上下文的实体维护两个字典。一个字典的键是实体本身,另一个字典的键是实体 id,它本质上是实体 url。在 AttachTo 方法中,上下文验证两个字典,如果在其中任何一个中找到条目,则抛出 InvalidOperationException。但是 UpdateObject 方法只验证 key 是实体本身的字典,如果没有找到则失败。

DataServiceContext 似乎假设只能对同一个实体进行修改,默认情况下它不支持将实体作为一个整体替换为新实例。但是逻辑使用标准字典类和默认比较器,因此在为 TableRecord 实现 IEquatable 接口后一切正常。

所以对我来说解决方案是:

[DataServiceKey("PartitionKey", "RowKey")]
public class TableRecord: IEquatable<TableRecord>
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTime Timestamp { get; set; }
    public string Data { get; set; }

    public bool Equals(TableRecord other)
    {
        if (other == null)
            return false;
        return PartitionKey.Equals(other.PartitionKey) && RowKey.Equals(other.RowKey);
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as TableRecord);
    }

    public override int GetHashCode()
    {
        return PartitionKey.GetHashCode() ^ RowKey.GetHashCode();
    }
}

【问题讨论】:

    标签: c# azure wcf-data-services azure-table-storage tableservicescontext


    【解决方案1】:

    对此的解决方案是,如果存在现有实体,您需要 Detach() 它和 AttachTo() 您的新实体。然后做你想做的更新。

    我写了一些代码来做到这一点。它还避免了抛出异常,尽管我不确定哪种方法更快。

            /// <summary>
            /// Detach any existing rows with the same keys (if necessary), then attach to this object using the "*" ETag
            /// </summary>
            /// <param name="newEntity"></param>
            protected virtual void SafeAttach(TableServiceEntity newEntity)
            {
                TableServiceEntity entity = GetExistingRow(newEntity.PartitionKey, newEntity.RowKey);
                if(entity != null)
                {
                    base.Detach(entity);
                }
    
                base.AttachTo("MY_TABLE_NAME_GOES_HERE", newEntity, "*");
            }
    
            private TableServiceEntity GetExistingRow(string partitionKey, string rowKey)
            {
                var query = (from e in base.Entities
                             where e.Entity is TableServiceEntity
                             && ((TableServiceEntity)e.Entity).RowKey == rowKey
                             && ((TableServiceEntity)e.Entity).PartitionKey == partitionKey
                             select (TableServiceEntity)e.Entity);
    
                RetrierFunctionResult<TableServiceEntity> r = StorageOperationRetrier.Execute(() =>
                {
                    return query.FirstOrDefault();
                });
    
                return r.Result;
            }
    

    要使用它,您可以将 try/catch 块替换为对 SafeAttach(storeRec) 的调用。

    请注意,这种方法会破坏表存储的内置并发检查。你基本上得到了最后写入获胜的行为。这可能会或可能不会接受,这取决于您的情况。

    此外,如果您打算以此方式继续工作,您可能需要设置MergeOption.NoTracking。无论如何,您基本上都是在模拟这种行为,并且禁用实体跟踪有一些性能优势。

    【讨论】:

    • 我只是使用 MergeOption.NotTracking,更简单
    • 在我的方法中,该表有一个有效负载字段数据,其中最新版本的对象序列化。所以最后写入获胜的行为确实是我正在寻找的。但看起来我错过了 NoTracking 选项背后的想法 - 它最适合这种情况。
    【解决方案2】:

    【讨论】:

    • 感谢您提供有趣的链接。不幸的是,这没有帮助 - 我仍然遇到同样的错误 - 它们甚至在发出任何请求之前就被抛出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多