drinkrate/DrinkRateAPI/Services/ProductCompanyTableCoupleService.cs
martinshoob b7677bc139 Create product-company table coupling, fix one-to-one relationship
Introduce a new entity to couple product and company tables.
2025-08-11 21:03:28 +02:00

51 lines
No EOL
1.9 KiB
C#

using DrinkRateAPI.ApiModels.ProductTable;
using DrinkRateAPI.Contexts;
using DrinkRateAPI.DbEntities;
using DrinkRateAPI.Exceptions;
using Microsoft.EntityFrameworkCore;
namespace DrinkRateAPI.Services;
public class ProductCompanyTableCoupleService(ApplicationDbContext context)
{
private ApplicationDbContext _context = context;
public async Task<ProductCompanyTableCouplePostResponse> PostProductCompanyTableCoupleAsync(
ProductCompanyTableCouplePost productCompanyTableCouplePost)
{
var companyTable = new DbCompanyTable
{
CompanyTableName = productCompanyTableCouplePost.CompanyTableName,
ProductTable = new DbProductTable
{
ProductTableName = productCompanyTableCouplePost.ProductTableName
}
};
_context.CompanyTable.Add(companyTable);
await _context.SaveChangesAsync();
return await GetProductCompanyTableCouplePostResponse(
productCompanyTableCouplePost.ProductTableName,
productCompanyTableCouplePost.CompanyTableName);
}
private async Task<ProductCompanyTableCouplePostResponse> GetProductCompanyTableCouplePostResponse(
string productTableName, string companyTableName)
{
var productTable =
await _context.ProductTable.FirstOrDefaultAsync(x => x.ProductTableName == productTableName) ??
throw new NotFoundException();
var companyTable =
await _context.CompanyTable.FirstOrDefaultAsync(x => x.CompanyTableName == companyTableName) ??
throw new NotFoundException();
return new ProductCompanyTableCouplePostResponse
{
ProductTableName = productTable.ProductTableName,
ProductTableId = productTable.Id.ToString(),
CompanyTableName = companyTable.CompanyTableName,
CompanyTableId = companyTable.Id.ToString()
};
}
}