我正在寻找一个简单的 C# 程序来将数据插入到 Azure blob 表存储中。 有人可以帮忙吗?
请告诉我下面的代码有什么问题?(该代码不会抛出任何错误,但只是不创建任何表/插入数据)
using System;
using System.Threading.Tasks;
using Azure.Data.Tables;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using TableEntity = Microsoft.WindowsAzure.Storage.Table.TableEntity;
using TableClientConfiguration = Microsoft.Azure.Cosmos.Table.TableClientConfiguration;
public class CustomerEntity : TableEntity
{
public CustomerEntity(string lastName, string firstName)
{
this.PartitionKey = lastName;
this.RowKey = firstName;
}
public CustomerEntity() { } // the parameter-less constructor must be provided
public string Email { get; set; }
public string PhoneNumber { get; set; }
}
class Program
{
static void Main(string[] args) {
var tableName = "TestTempTable";
var storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=**********;AccountKey=*******/****==;EndpointSuffix=core.windows.net";
try
{
Console.WriteLine("START");
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference(tableName);
table.CreateIfNotExistsAsync();
Console.WriteLine($"CloudTable name is : {tableClient}");
// Create a new customer entity.
CustomerEntity customer1 = new CustomerEntity("Harp", "Walter");
customer1.Email = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2951505369515053074a4644" rel="noreferrer noopener nofollow">[email protected]</a>";
customer1.PhoneNumber = "1234568";
table.ExecuteAsync(TableOperation.Insert(customer1));
Console.WriteLine("Records Inserted");
Console.WriteLine("END");
}
catch (Exception e)
{
Console.WriteLine("Encountered Exception - "+e);
}
}
}
谢谢, 保罗。
最佳答案
您的程序不抛出任何错误并且不插入实体的原因是您没有等待异步操作并且您的程序在成功之前终止。这就是为什么“插入记录”之类的行像正常程序执行一样运行。考虑在程序中的这两行中使用 await
:
await table.CreateIfNotExistsAsync();
await table.ExecuteAsync(TableOperation.Insert(customer1));
关于azure-table-storage - 如何将数据插入Azure表存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70031284/