【发布时间】: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