Click here to Skip to main content
15,884,637 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have created windows form application with c# and sql server 2019
i have atable inside my sql server database named InevtoryCode
i want to update my table with async and await . the problem is my code already run but i think thats is not the perfect way to update my table with async and await.
so can any one help me to make my code more cleaner

What I have tried:

C#
public async Task<inventorystore> UpdateStoreAsync(InventoryStore inventory)
        {
            InventoryStore updatedStore = await UpdateInventoryWithAwait(inventory);
            return updatedStore;
        }
        private async Task<inventorystore> UpdateInventoryWithAwait(InventoryStore inventory)
        {
            //validations
            if (string.IsNullOrWhiteSpace(inventory.Name))
            {
                throw new ApplicationException("Name is required");
            }
            var updatedInventory = _db.Inventories.Find(inventory.Id);
            updatedInventory.Name = inventory.Name;
            updatedInventory.AccountNumber = inventory.AccountNumber;
            updatedInventory.CostOfGoodSoldAccountNumber = inventory.CostOfGoodSoldAccountNumber;
            _db.SaveChanges();
            return updatedInventory;
        }
Posted
Updated 25-Nov-21 22:45pm
v3
Comments
Maciej Los 25-Nov-21 14:50pm    
As to me - you don't really need this.
Abuamer 25-Nov-21 15:40pm    
please more explain
#realJSOP 26-Nov-21 4:15am    
He means you don't need await. It's unnecessary.
Abuamer 26-Nov-21 5:56am    
No it works fine
BillWoodruff 25-Nov-21 23:38pm    
What happens now when you run your code ? Errors ? Unexpected bresults ?

1 solution

Entity Framework provides async methods for various operations. Your code should use those.
C#
public async Task<InventoryStore> UpdateStoreAsync(InventoryStore inventory)
{
    if (string.IsNullOrWhiteSpace(inventory.Name))
    {
        throw new ArgumentException(message: "Name is required", paramName: nameof(inventory));
    }

    var updatedInventory = await _db.Inventories.FindAsync(inventory.Id);
    if (updatedInventory is null)
    {
        throw new ArgumentException(message: $"Inventory store {inventory.Id} does not exist", paramName: nameof(inventory));
    }
    
    updatedInventory.Name = inventory.Name;
    updatedInventory.AccountNumber = inventory.AccountNumber;
    updatedInventory.CostOfGoodSoldAccountNumber = inventory.CostOfGoodSoldAccountNumber;
    await _db.SaveChangesAsync();
    
    return updatedInventory;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900