背景
假设我有一个Azure表实体
class MyEntity : TableEntity
{
public string LongString { get; set; }
public bool IsCompressed { get; set; }
}
如果LongString
>64KB(Azure属性限制(,我想保存压缩的LongString
。为此,我有两个功能Compress(string)
和Decompress(string)
目前,在每次插入之前,我都会检查LongString
的长度,如果它>64KB,我会设置LongString = Compress(LongString)
和IsCompressed = true
。每次Azure get操作后情况正好相反。
我想在整个代码中隐藏压缩选项,并将压缩和解压缩自包含在MyEntity
类中。
问题
在从azure表获取和设置实体之前和之后,是否有进行自定义操作的选项?类似。。。
class MyEntity : TableEntity
{
public string LongString { get; set; }
public string IsCompressed { get; set; }
public override void BeforeInsert()
{
if (LongString.Length > 64KB)
{
LongString = Compress(LongString);
IsCompressed = true;
}
}
public override void AfterGet()
{
if (IsCompressed)
{
LongString = Decompress(LongString);
IsCompressed = false;
}
}
}
一种可能性可能类似于以下代码:
public bool IsCompressed;
public string StoredString { get; set; }
private string longString;
[IgnoreProperty]
public string LongString
{
get
{
if (this.longString == null)
{
if (IsCompressed)
{
this.longString = DeCompress(StoredString);
}
else
{
this.longString = StoredString;
}
}
return this.longString;
}
set
{
if (longString != value)
{
this.longString = value;
if (this.longString.Length > 64KB)
{
IsCompressed = true;
this.StoredString = Compress(this.longString);
}
}
}
}
但问问自己,总是保存压缩字符串是否不是更容易。
找到了一个使用ReadEntity
和WriteEntity
函数的解决方案。
class MyEntity : TableEntity
{
public string LongString { get; set; }
public bool IsCompressed { get; set; }
public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
{
base.ReadEntity(properties, operationContext);
if (IsCompressed)
{
LongString = Decompress(LongString);
IsCompressed = false;
}
}
public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
{
if (LongString.Length > 64KB)
{
LongString = Compress(LongString);
IsCompressed = true;
}
return base.WriteEntity(operationContext);
}
}
您不需要任何复杂度,只需创建计算属性即可写入表存储。而且您也不需要多个属性。因此,不需要具有具有IgnoreProperty属性的第二个属性。我在文本编辑器中键入了以下内容,但这应该会给你一些想法。
private string longString;
public bool IsCompressed { get; set; }
public string LongString
{
get
{
return IsCompressed ? DeCompress(longString) : longString;
}
set
{
if (String.IsNullOrWhiteSpace(value) || value.Length < 64KB)
{
IsCompressed = false;
longString = value;
}
else (value.Length > 64KB)
{
IsCompressed = true;
longString = Compress(value);
}
}
}