gpt4 book ai didi

c# - Azure 表存储插入或合并

转载 作者:行者123 更新时间:2023-12-02 07:37:59 25 4
gpt4 key购买 nike

我有一个包含一些数据的 Azure 表存储。我需要更新表中所有记录的一个属性。我知道每个项目的分区键和行键。不过,我的 CSV 文件中可能有新项目。

我需要做的是:

  • 如果基于 ParitionKey 和 RowKey 在表存储中找到一项,我想更新一个属性:名称。
  • 如果在表中找不到某个项目,则必须将其插入,但我还有更多属性需要填写:姓名、电子邮件、地址

我正在尝试使用 InsertOrMerge,但出现 Etag 异常,如果未找到该项目并且需要插入,如何设置更多属性?

var storageAccount = CloudStorageAccount.Parse(connectionString);
var cloudTableClient = storageAccount.CreateCloudTableClient();
var ct = cloudTableClient.GetTableReference("mytable");

var item = new Item()
{
PartitionKey = "PARTITIONID",
RowKey = "ROWID",
Name = "DEMO",
};

var to = TableOperation.Merge(code);
var result = await ct.ExecuteAsync(to);

最佳答案

当我使用Merge操作表中不存在的实体时,我也遇到了etag异常。

System.ArgumentException:“合并需要 ETag(可能是 '*' 通配符)。”

您的需求可以通过RetrieveInsertOrMerge来实现。

向您的 Item 类添加两个属性 EmailAddress

 public class Item: TableEntity
{
public Item(String PartitionKey, String RowKey, String Name, String Email=null, String Address=null)
{
this.RowKey = RowKey ;
this.PartitionKey = PartitionKey;
this.Name = Name;
this.Email = Email;
this.Address = Address;
}

public Item(){}

public String Name { get; set; }

public String Email { get; set; }

public String Address { get; set; }

}

添加 if 开关来告知要加载哪些属性。

 TableOperation to = TableOperation.Retrieve<Item>("PK","RK");

TableResult tr = table.ExecuteAync(to).Result;

var item;

if (tr != null)
{
item = new Item
{
PartitionKey = "PARTITIONID",
RowKey = "ROWID",
Name = "DEMO",
}
}
else
{
item = new Item
{
PartitionKey = "PARTITIONID",
RowKey = "ROWID",
Name = "DEMO",
Email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc88998f88bc99849d918c9099d29f9391" rel="noreferrer noopener nofollow">[email protected]</a>",
Address = "Britain"
}
}

to = TableOperation.InsertOrMerge(item);

tr = await ct.ExecuteAysnc(to).Result;

。当您执行InsertOrMerge时,

  • 如果该项目存在,其内容(名称)将由您的新项目更新。
  • 如果不存在,则会按预期插入。

关于c# - Azure 表存储插入或合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51034542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com