azure-table-storage - 如何将数据插入Azure表存储

标签 azure-table-storage

我正在寻找一个简单的 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/

相关文章:

Azure 表存储拒绝属性值为接口(interface)的实体

asp.net-mvc - 如何减少Azure表存储延迟?

rest - 访问 Azure 表实体

Azure表存储: Xml serialization for TableContinuationToken

Azure表: how to use partition key and row key when entities have only one key?

azure - Azure 表存储中的 PartitionKey 和 RowKey 必须是字符串吗?

c# - Linux系统上的Azure表/Blob/队列随机超时(k8s .net core 3应用程序)

c# - Azure 2012 年 10 月 sdk - 如何删除表实体而不先检索它?

azure - Umbraco 5 与 MVC4 和 Azure

azure - 更新 Azure 表存储记录时如何避免竞争条件