### Get Products Query with Filtering Source: https://context7.com/calabonga/unitofwork/llms.txt Returns an IQueryable for products with a price greater than 100, ordered by price descending. Uses NoTracking. ```csharp public IQueryable GetProductsQuery() { var repository = _unitOfWork.GetRepository(); return repository.GetAll( predicate: p => p.Price > 100, orderBy: q => q.OrderByDescending(p => p.Price), trackingType: TrackingType.NoTracking); } ``` -------------------------------- ### Get Product Names Async with Projection Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves a list of product names for products with a price greater than 0 using a selector for projection. ```csharp public async Task> GetProductNamesAsync() { var repository = _unitOfWork.GetRepository(); return await repository.GetAllAsync( selector: p => p.Name, predicate: p => p.Price > 0); } ``` -------------------------------- ### Get Paged Products Async Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves a paginated list of products with filtering, ordering, and inclusion of related entities. Specifies page index and size. ```csharp using Calabonga.PagedListCore; public async Task> GetPagedProductsAsync(int pageIndex, int pageSize) { var repository = _unitOfWork.GetRepository(); return await repository.GetPagedListAsync( predicate: p => p.Price > 0, orderBy: q => q.OrderBy(p => p.Name), include: q => q.Include(p => p.Category), pageIndex: pageIndex, // Индекс страницы (начиная с 0) pageSize: pageSize, // Количество записей на странице trackingType: TrackingType.NoTracking); } ``` -------------------------------- ### Get All Products by Category Async Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves a list of products filtered by category, ordered by name, and includes the related category entity. Uses NoTracking to improve performance. ```csharp public async Task> GetProductsByCategoryAsync(int categoryId) { var repository = _unitOfWork.GetRepository(); return await repository.GetAllAsync( predicate: p => p.CategoryId == categoryId, orderBy: q => q.OrderBy(p => p.Name), include: q => q.Include(p => p.Category), trackingType: TrackingType.NoTracking, ignoreQueryFilters: false, ignoreAutoIncludes: false); } ``` -------------------------------- ### Get Paged Product DTOs Async with Projection Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves a paginated list of Product DTOs, projecting specific properties including the related category name. ```csharp public async Task> GetPagedProductDtosAsync(int pageIndex, int pageSize) { var repository = _unitOfWork.GetRepository(); return await repository.GetPagedListAsync( selector: p => new ProductDto { Id = p.Id, Name = p.Name, CategoryName = p.Category!.Name }, predicate: p => p.Price > 0, orderBy: q => q.OrderBy(p => p.Name), pageIndex: pageIndex, pageSize: pageSize); } ``` -------------------------------- ### Get Repository for Entity Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieve a typed repository for a specific entity. This method is fundamental for all repository operations. It can be used with or without specifying custom repository presence. ```csharp public class ProductController : ControllerBase { private readonly IUnitOfWork _unitOfWork; public ProductController(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; [HttpGet] public async Task GetAll() { var repository = _unitOfWork.GetRepository(); var products = await repository.GetAllAsync( predicate: p => p.Price > 0, orderBy: q => q.OrderByDescending(p => p.Price), include: q => q.Include(p => p.Category)); return Ok(products); } ``` -------------------------------- ### Get First or Default Entity Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieve the first entity matching criteria, with options for ordering, includes, and projections. Supports asynchronous operations and non-tracking queries for performance. The `selector` can transform the entity into a DTO. ```csharp public async Task GetCheapestProductAsync() { var repository = _unitOfWork.GetRepository(); var product = await repository.GetFirstOrDefaultAsync( predicate: p => p.Price > 0, orderBy: q => q.OrderBy(p => p.Price), include: q => q.Include(p => p.Category), trackingType: TrackingType.NoTracking); return product; } // С проекцией в DTO public async Task GetProductDtoAsync(int id) { var repository = _unitOfWork.GetRepository(); return await repository.GetFirstOrDefaultAsync( selector: p => new ProductDto { Id = p.Id, Name = p.Name, CategoryName = p.Category!.Name }, predicate: p => p.Id == id); } public class ProductDto { public int Id { get; set; } public string Name { get; set; } = string.Empty; public string CategoryName { get; set; } = string.Empty; } ``` -------------------------------- ### Mass Update Prices Async using ExecuteUpdate Source: https://context7.com/calabonga/unitofwork/llms.txt Performs a mass update on all product prices by increasing them by a given percentage. This operation executes immediately without requiring SaveChanges. ```csharp public async Task IncreaseAllPricesAsync(decimal percentage) { var repository = _unitOfWork.GetRepository(); return await repository.ExecuteUpdateAsync( setters => setters.SetProperty( p => p.Price, p => p.Price * (1 + percentage / 100)), CancellationToken.None); } ``` -------------------------------- ### Use UnitOfWorkFactory in a Background Service Source: https://context7.com/calabonga/unitofwork/llms.txt Demonstrates how to inject and use the IUnitOfWorkFactory to create and manage UnitOfWork instances within a background service. Ensure proper disposal of the UnitOfWork instance using a 'using' statement. ```csharp public class BackgroundService : IHostedService { private readonly IUnitOfWorkFactory _factory; public BackgroundService(IUnitOfWorkFactory factory) { _factory = factory; } public async Task DoWorkAsync() { using var unitOfWork = _factory.CreateUnitOfWork(); var repository = unitOfWork.GetRepository(); var products = await repository.GetAllAsync(); // Обработка... await unitOfWork.SaveChangesAsync(); } } ``` -------------------------------- ### Update Single Product Async Source: https://context7.com/calabonga/unitofwork/llms.txt Finds a product by ID, updates its name and price, and then saves the changes using the Unit of Work. ```csharp public async Task UpdateProductAsync(int id, string newName, decimal newPrice) { var repository = _unitOfWork.GetRepository(); var product = await repository.FindAsync(id); if (product == null) return; product.Name = newName; product.Price = newPrice; repository.Update(product); await _unitOfWork.SaveChangesAsync(); } ``` -------------------------------- ### Update Multiple Products Async Source: https://context7.com/calabonga/unitofwork/llms.txt Updates a collection of products and saves the changes using the Unit of Work. ```csharp public async Task UpdateMultipleProductsAsync(IEnumerable products) { var repository = _unitOfWork.GetRepository(); repository.Update(products); await _unitOfWork.SaveChangesAsync(); } ``` -------------------------------- ### Register Custom Repository Source: https://context7.com/calabonga/unitofwork/llms.txt Register a custom repository with additional business logic. Ensure the UnitOfWork is registered first. Usage involves injecting IUnitOfWork and casting the retrieved repository to the custom interface. ```csharp public interface IProductRepository : IRepository { Task> GetActiveProductsAsync(); } public class ProductRepository : Repository, IProductRepository { public ProductRepository(DbContext context) : base(context) { } public async Task> GetActiveProductsAsync() { return await GetAllAsync( predicate: p => p.Price > 0, orderBy: q => q.OrderBy(p => p.Name)); } } // Регистрация builder.Services.AddUnitOfWork(); builder.Services.AddCustomRepository(); // Использование public class ProductService { private readonly IUnitOfWork _unitOfWork; public ProductService(IUnitOfWork unitOfWork) => _unitOfWork = unitOfWork; public async Task> GetActiveProducts() { // Получение кастомного репозитория var repository = _unitOfWork.GetRepository(hasCustomRepository: true) as IProductRepository; return await repository!.GetActiveProductsAsync(); } } ``` -------------------------------- ### Register Multiple DbContexts Source: https://context7.com/calabonga/unitofwork/llms.txt Configures the library to handle multiple database contexts simultaneously within the same application. ```csharp public class OrderDbContext : DbContext { public OrderDbContext(DbContextOptions options) : base(options) { } public DbSet Orders => Set(); } public class InventoryDbContext : DbContext { public InventoryDbContext(DbContextOptions options) : base(options) { } public DbSet Stocks => Set(); } // Регистрация двух контекстов builder.Services.AddUnitOfWork(); // Или трёх контекстов builder.Services.AddUnitOfWork(); // Использование в сервисе public class OrderService { private readonly IUnitOfWork _orderUow; private readonly IUnitOfWork _inventoryUow; public OrderService( IUnitOfWork orderUow, IUnitOfWork inventoryUow) { _orderUow = orderUow; _inventoryUow = inventoryUow; } public async Task ProcessOrderAsync(int orderId) { var orderRepo = _orderUow.GetRepository(); var stockRepo = _inventoryUow.GetRepository(); var order = await orderRepo.FindAsync(orderId); var stock = await stockRepo.GetFirstOrDefaultAsync(s => s.ProductId == order!.ProductId); // Бизнес-логика... } } ``` -------------------------------- ### Insert Source: https://context7.com/calabonga/unitofwork/llms.txt Adds new entities to the database context. ```APIDOC ## Insert ### Description Adds a single entity or a collection of entities to the repository. Changes must be persisted using SaveChanges/SaveChangesAsync. ### Methods - Insert(TEntity entity) - InsertAsync(TEntity entity) - InsertAsync(IEnumerable entities) ### Parameters - **entity/entities** (TEntity/IEnumerable) - Required - The entity or list of entities to add. ``` -------------------------------- ### Register UnitOfWorkFactory Source: https://context7.com/calabonga/unitofwork/llms.txt Register the UnitOfWorkFactory with the dependency injection container. This is typically done in the application's startup configuration. ```csharp builder.Services.AddUnitOfWorkFactory(); ``` -------------------------------- ### Handle Paged List Result Source: https://context7.com/calabonga/unitofwork/llms.txt Demonstrates how to consume the IPagedList result, accessing properties like Items, PageIndex, PageSize, TotalCount, and pagination booleans. ```csharp public async Task GetProducts(int page = 0, int size = 20) { var pagedList = await GetPagedProductsAsync(page, size); return Ok(new { Items = pagedList.Items, PageIndex = pagedList.PageIndex, PageSize = pagedList.PageSize, TotalCount = pagedList.TotalCount, TotalPages = pagedList.TotalPages, HasPreviousPage = pagedList.HasPreviousPage, HasNextPage = pagedList.HasNextPage }); } ``` -------------------------------- ### AddCustomRepository Source: https://context7.com/calabonga/unitofwork/llms.txt Registers a custom repository implementation with the Unit of Work container to support specialized business logic. ```APIDOC ## AddCustomRepository ### Description Registers a custom repository class that extends the base repository functionality for a specific entity type. ### Method Dependency Injection (Service Registration) ### Parameters - **TEntity** (Type) - Required - The entity type managed by the repository. - **TRepository** (Type) - Required - The custom repository implementation class. ``` -------------------------------- ### GetRepository Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves a repository instance for a specific entity type from the Unit of Work. ```APIDOC ## GetRepository ### Description Retrieves a repository instance for the specified entity type to perform CRUD operations. ### Method GetRepository() ### Parameters - **TEntity** (Type) - Required - The entity type for which the repository is requested. ``` -------------------------------- ### Find Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves an entity by its primary key. ```APIDOC ## Find ### Description Finds an entity by its primary key value(s). Supports both single and composite keys. ### Methods - Find(params object[] keyValues) - FindAsync(params object[] keyValues) ### Parameters - **keyValues** (object[]) - Required - The primary key values to search for. ``` -------------------------------- ### Find Entity by Primary Key Source: https://context7.com/calabonga/unitofwork/llms.txt Asynchronously or synchronously find an entity using its primary key. Supports single and composite keys. Ensure the correct key types and values are provided for composite keys. ```csharp public async Task GetByIdAsync(int id) { var repository = _unitOfWork.GetRepository(); // Асинхронный поиск var product = await repository.FindAsync(id); return product; } public async Task GetByCompositeKeyAsync(int key1, string key2) { var repository = _unitOfWork.GetRepository(); // Поиск по составному ключу var entity = await repository.FindAsync(new object[] { key1, key2 }); return entity; } public Product? GetByIdSync(int id) { var repository = _unitOfWork.GetRepository(); // Синхронный поиск return repository.Find(id); } ``` -------------------------------- ### GetFirstOrDefault Source: https://context7.com/calabonga/unitofwork/llms.txt Retrieves the first record matching specific criteria. ```APIDOC ## GetFirstOrDefault ### Description Retrieves the first entity matching the provided predicate, with support for sorting, inclusion of related data, and projection into DTOs. ### Methods - GetFirstOrDefaultAsync(...) ### Parameters - **predicate** (Expression>) - Optional - Filter condition. - **orderBy** (Func, IOrderedQueryable>) - Optional - Sorting logic. - **include** (Func, IIncludableQueryable>) - Optional - Related data to include. - **selector** (Expression>) - Optional - Projection selector. ``` -------------------------------- ### Register Unit of Work in DI Source: https://context7.com/calabonga/unitofwork/llms.txt Registers IUnitOfWork in the ASP.NET Core dependency injection container. Supports specifying the service lifetime. ```csharp using Calabonga.UnitOfWork; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; // Модель сущности public class Product { public int Id { get; set; } public string Name { get; set; } = string.Empty; public decimal Price { get; set; } public int CategoryId { get; set; } public Category? Category { get; set; } } public class Category { public int Id { get; set; } public string Name { get; set; } = string.Empty; public ICollection Products { get; set; } = new List(); } // DbContext public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions options) : base(options) { } public DbSet Products => Set(); public DbSet Categories => Set(); } // Program.cs / Startup.cs var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); // Регистрация Unit of Work с временем жизни Scoped (по умолчанию) builder.Services.AddUnitOfWork(); // Или с явным указанием времени жизни builder.Services.AddUnitOfWork(ServiceLifetime.Scoped); ``` -------------------------------- ### Insert Single and Batch Entities Source: https://context7.com/calabonga/unitofwork/llms.txt Perform synchronous and asynchronous insertions of one or multiple entities. Remember to call SaveChangesAsync or SaveChanges after inserting entities to persist the changes. ```csharp public async Task CreateProductAsync(string name, decimal price, int categoryId) { var repository = _unitOfWork.GetRepository(); // Вставка одной сущности var product = new Product { Name = name, Price = price, CategoryId = categoryId }; var entry = await repository.InsertAsync(product); await _unitOfWork.SaveChangesAsync(); return entry.Entity; } public async Task CreateProductsBatchAsync(List products) { var repository = _unitOfWork.GetRepository(); // Вставка нескольких сущностей await repository.InsertAsync(products); await _unitOfWork.SaveChangesAsync(); } public void CreateProductSync(Product product) { var repository = _unitOfWork.GetRepository(); // Синхронная вставка repository.Insert(product); _unitOfWork.SaveChanges(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.