79 lines
2.9 KiB
C#
79 lines
2.9 KiB
C#
using AyCode.Core.Extensions;
|
|
using AyCode.Database.DbSets.Profiles;
|
|
using AyCode.Interfaces.Addresses;
|
|
using AyCode.Interfaces.Entities;
|
|
using AyCode.Interfaces.Profiles;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.ChangeTracking;
|
|
using TIAM.Database.DbSets.Transfers;
|
|
using TIAM.Database.DbSets.Users;
|
|
using TIAM.Entities.Addresses;
|
|
using TIAM.Entities.Products;
|
|
using TIAM.Entities.Profiles;
|
|
using TIAM.Entities.Users;
|
|
|
|
namespace TIAM.Database.DbSets.Products;
|
|
|
|
public static class ProductDbSetExtensions
|
|
{
|
|
#region Add, Update, Remove
|
|
|
|
public static bool AddProduct(this IProductDbSet ctx, Product product)
|
|
{
|
|
if (product.Id.IsNullOrEmpty()) product.Id = Guid.NewGuid();
|
|
|
|
if (product.Profile == null!)
|
|
product.SetProfile((Activator.CreateInstance(typeof(Profile), product.ProfileId, product.Name) as Profile)!);
|
|
|
|
if (product.Profile!.Address == null!)
|
|
product.Profile.SetAddress((Activator.CreateInstance(typeof(Address), product.Profile.AddressId, product.Name) as Address)!);
|
|
|
|
return ctx.Products.Add(product).State == EntityState.Added;
|
|
}
|
|
|
|
public static bool UpdateProduct(this IProductDbSet ctx, Product product)
|
|
{
|
|
return ctx.Products.Update(product).State == EntityState.Modified;
|
|
}
|
|
|
|
private static bool RemoveProduct(this IProductDbSet ctx, Product product)
|
|
{
|
|
ctx.RemoveProfile(product.ProfileId);
|
|
ctx.RemoveUserProductMappingsByProductId(product.Id);
|
|
ctx.RemoveTransferDestinationToProductByProductId(product.Id);
|
|
|
|
//TODO: Transfer, etc... - J.
|
|
return ctx.Products.Remove(product).State == EntityState.Deleted;
|
|
}
|
|
|
|
public static bool RemoveProduct(this IProductDbSet ctx, Guid productId)
|
|
{
|
|
var product = ctx.GetProductById(productId);
|
|
return product == null || ctx.RemoveProduct(product);
|
|
}
|
|
|
|
public static bool RemoveProductsByCompanyId(this IProductDbSet ctx, Guid companyId)
|
|
{
|
|
var products = ctx.GetProductsByCompanyId(companyId);
|
|
|
|
foreach (var product in products)
|
|
ctx.RemoveProduct(product);
|
|
|
|
return true;
|
|
}
|
|
#endregion Add, Update, Remove
|
|
|
|
public static IQueryable<Product> ProductsWithUserRelations(this IProductDbSet ctx, bool autoInclude = true)
|
|
=> autoInclude
|
|
? ctx.Products
|
|
.Include(x => x.UserProductMappings)
|
|
.ThenInclude(x => x.User)
|
|
: ctx.Products;
|
|
|
|
public static Product? GetProductById(this IProductDbSet ctx, Guid productId, bool includeUsers = true)
|
|
=> ctx.ProductsWithUserRelations(includeUsers).FirstOrDefault(x => x.Id == productId);
|
|
|
|
public static IQueryable<Product> GetProductsByCompanyId(this IProductDbSet ctx, Guid serviceProviderId, bool includeUsers = true)
|
|
=> ctx.ProductsWithUserRelations(includeUsers).Where(x => x.ServiceProviderId == serviceProviderId);
|
|
|
|
} |