Как автоматически сгенерировать RowKey в хранилище таблиц Azure с помощью C#
Я пытаюсь изменить RowKey с предварительно определенной фамилии из учебника Micorosft Docs: https://docs.microsoft.com/en-us/azure/cosmos-db/table-storage-how-to-use-dotnet, к уникальному значению.
Это мой текущий код:
private void storeuserinput(Activity activity)
{
var uid = activity.From.Id;
var uname = activity.From.Name;
if (activity.Text?.ToLower().ToString() == "no" || activity.Text?.ToLower().ToString() == "NO" || activity.Text?.ToLower().ToString() == "No" || activity.Text?.ToLower().ToString() == "Nope" || activity.Text?.ToLower().ToString() == "nope")
{
var userinput = firstmessage;
string connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
// Parse the connection string and return a reference to the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
// Retrieve a reference to the table.
CloudTable table = tableClient.GetTableReference("UnansweredChatBot");
// Create the table if it doesn't exist.
table.CreateIfNotExists();
// Create a new customer entity.
CustomerEntity customer1 = new CustomerEntity("NoSolution", "Smith");
customer1.Query = firstmessage;
// Create the TableOperation object that inserts the customer entity.
TableOperation insertOperation = TableOperation.Insert(customer1);
// Execute the insert operation.
table.Execute(insertOperation);
}
//extract other data from "activity" object
//your code logic here
//store data in your table storage
//Note: specifcial scenario of user send attachment
}
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 Query { get; set; }
}
Любая помощь в решении этой проблемы будет высоко ценится!
1 ответ
В своем классе сущности клиента вы вызываете конструктор
public CustomerEntity(string lastName, string firstName)
{
this.PartitionKey = lastName;
this.RowKey = firstName;
}
Поэтому, когда вы инициализируете новый объект, вы проходите через два параметра, как определено в конструкторе, firstname
а также lastname
,
новый
Они устанавливаются по имени конструктором и не имеют никакого значения вне их контекста (то есть в хранилище таблиц).
CustomerEntity customer1 = new CustomerEntity("NoSolution", "Smith");
В вашем коде все, что вам нужно сделать, это изменить ваш конструктор, чтобы быть похожим
public CustomerEntity(string requesterName, string uniqueRowKey)
{
this.PartitionKey = requesterName ;
this.RowKey = uniqueRowKey;
}
Ваш RowKey должен быть уникальным, а ключ разделения используется для облегчения поиска, группируя строки одинаковых типов. Затем вы можете перейти к своему конструктору следующим образом:
string rowKey = Guid.NewGuid().ToString("N"); //This give you a unique guid with no hyphens.
CustomerEntity customer1 = new CustomerEntity("John Smith", rowKey);
Который вставил бы вашу сущность с этим набором в Ключ раздела и Ключ строки соответственно.
Это то, что вы искали?