I'm trying to manipulate data on a webpage and I have an API that can do that, but I ran into some problems.
There is a part in my code, where I insert-, manipulate and then update data to the webpage. The API uses asynchronous methods to insert and update data to the webpage, so I can't change that.
Here is the code, where the problem occurs:
namespace Web
{
class WebDatabase
{
WebApi api;
internal static async Task InsertCategory(string category)
{
await api.Insert(category); // Insert data to the database
//Some manipulation on the category
//..
//..
await api.GetCategoryIdFromDatabase(category); // Getting id of data from the database
await api.Update(category); // Updating that data based on id in the database
}
}
}
As you can see, after I insert the data into the database I have to get the automatically generated ID from the database in order to be able to update the data that I manipulated, but sometimes it inserts it before trying to get the ID and sometimes not! How can I fix it? I must be doing something wrong, but I think I kinda tried everything to make it work, but still no success :(
Here is the rest of the code, maybe it will help you to better see what's going on.
Main
namespace Main
{
class Program
{
Thread thread;
private void buttonClick(object sender, EventArgs e)
{
if (thread != null && thread.IsAlive)
{
Console.WriteLine("The process is still going!");
return;
}
thread = new Thread(Send);
thread.Start();
}
private async void Send()
{
await WebDatabase.SendCategoryList(category);
}
}
}
WebDatabase
namespace Web
{
class WebDatabase
{
WebApi api;
internal static async Task SendCategoryList(string category)
{
await api.Insert(category); // Inserting data to the database
//Some manipulation on the category
//..
//..
//
await api.GetCategoryIdFromDatabase(category); // Trying to get ID from database, but the data is not there yet, so it throws an error
await api.Update(category); // Now I can't update my poor category in the database :(
}
}
}
API
namespace API
{
class WebApi
{
WebAPI webapi = new WebAPI();
public async Task Insert(List<string> categoriesList)
{
for (int i = 0; i < categoriesList.Count; i++)
{
await Update(categoriesList[i]);
}
}
public async Task Update(string categories)
{
await webapi.Category.Add(categories);
}
public async Task GetCategoryIdFromDatabase(string categories)
{
await webapi.Category.GetAll().Result.FirstOrDefault(productCategory => productCategory.name.Trim().ToLower() == category.name.Trim().ToLower()).id.Value;
}
}
}
Any help would be greatly appreciated!