C#TableEntity在插入操作后保留IgnoredProperty

时间:2020-05-13 09:33:24

标签: c# azure azure-table-storage

我有以下实现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;

现在奇怪的是, insertedEntity 包含MyIgnoredProperty,尽管我希望它不包含它。

有人可以解释为什么会这样吗?

顺便说一句,如果我使用以下代码显式检索实体,则不会在数据库中也未设置MyIgnoredProperty。符合预期。

...
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;

2 个答案:

答案 0 :(得分:1)

也许是ExecuteAsync的问题,它返回与sended相同的对象,但不应用attribute, 这是一种解决方法,它是一个脚本,可复制除具有特定属性的属性以外的所有属性值

    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 :(得分:1)

我不确定100%的安全性(因为我无法找到它的代码),但我相信这是由SDK完成的。

我相信SDK的作用是在插入实体时进行序列化时,通过删除标记为IgnoreProperty的属性来创建JSON有效负载。但是,您的TableEntity对象(在您的情况下为entity)仍然具有此属性。

SDK收到响应后,将仅更新ETag的{​​{1}}和Timestamp属性,并在entity中返回该对象。

相关问题