C# TableEntity在插入操作后保持IgnoredProperty。

问题描述 投票:0回答:1

我有以下实现TableEntity的类。

public class MyEntity : TableEntity
{
    public string MyProperty { get; set; }

    [IgnoreProperty]
    public string MyIgnoredProperty { get; set; }
}

然后我有以下代码,插入一个TableEntity。

CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connectionString");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

ITableEntity entity = new MyEntity ();
entity.RowKey = "row";
entity.PartitionKey = "partition";
entity.MyIgnoredProperty = "ignored";

CloudTable currentTable = tableClient.GetTableReference("MyEntity");
TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);
TableResult result = await currentTable.ExecuteAsync(insertOrMergeOperation);
var insertedEntity = result.Result as ITableEntity;

现在奇怪的是 插入的实体 包含MyIgnoredProperty,尽管我希望它不应该包含它。

谁能解释一下为什么会出现这样的情况?

顺便说一下,如果我用下面的代码显式地检索实体,MyIgnoredProperty也不在DB中设置。正如我所期望的那样。

...
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connectionString");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

CloudTable currentTable = tableClient.GetTableReference(tableName);
TableOperation retrieveOperation = TableOperation.Retrieve<T>(partitionKey, rowKey);
TableResult tableResult = await currentTable.ExecuteAsync(retrieveOperation);
T result = (T)tableResult.Result;
c# azure azure-table-storage
1个回答
1
投票

也许是ExecuteAsync的一个问题,它返回的对象与发送的对象相同,没有应用属性,这里有一个变通的办法,是一个脚本,复制所有属性的值,除了一个有特定属性的属性。

    public static class Helper
    {
        public static MyEntity copyme(this MyEntity entity)
        {
            var copy = new MyEntity();
            var properties = typeof(MyEntity).GetProperties();

            var propertiesToExcept = typeof(MyEntity).GetProperties()
    .Where(prop => prop.IsDefined(typeof(IgnorePropertyAttribute), false));

            foreach (var prop in properties)
            {
                if (!propertiesToExcept.Any(acc => acc.Name == prop.Name))
                {
                    prop.SetValue(copy, prop.GetValue(entity));
                }
            }
            return copy;


        }
    }

为了使用这个功能,只需调用

                var obj = new MyEntity()
                {
                    MyIgnoredProperty = "toignore",
                    MyProperty = "tokeep"
                };
                var cleanobj = obj.copyme();

1
投票

我不是100%确定(因为我无法找到相关代码),但我相信这是SDK在做的。

我相信SDK所做的是,当你插入一个实体时,在序列化的时候,它正在通过删除标记为----------------------------------------------------------------的属性来创建一个JSON有效载荷。IgnoreProperty. 然而,你的 TableEntity 对象(entity 在你的例子中)仍然有这个属性。

一旦SDK接收到响应,它就会简单地更新你的 ETagTimestamp 贵公司 entity 并将该对象返回到 TableResult.Result.

© www.soinside.com 2019 - 2024. All rights reserved.