wahidustoz / durgerking

5 stars 1 forks source link

IAppDbContext [FromServices] #89

Closed wahidustoz closed 1 year ago

wahidustoz commented 1 year ago

IAppDbCotenxt'ni controllerga inject qilmasdan har bir actionga alohida inject qilib ishlatsa boladi.

Uning uchun action parameter'ga [FromServices] IAppDbContext dbContext, deb qo'shish kifoya.

Masalan.

[HttpPost]
public async Task<IActionResult> CreateProduct(
    [FromBody] CreateProductDto productdto,
    [FromServices] IAppDbContext dbContext)
{
    var created = dbContext.Products.Add(new Product
    {
        Id = Guid.NewGuid(),
        Name = productdto.Name,
        Description = productdto.Description,
        Price = productdto.Price,
        DiscountPercentage = productdto.DiscountPercentage,
        IsActive = productdto.IsActive,
        CreatedAt = DateTime.UtcNow,
        ModifiedAt = DateTime.UtcNow,
        CategoryId = productdto.CategoryId
    });

    await dbContext.SaveChangesAsync();

    return CreatedAtAction(nameof(GetProduct), new { id = created.Entity.Id }, new GetProductDto(created.Entity));
}