资阳市网站建设_网站建设公司_MySQL_seo优化
2026/1/17 9:54:08 网站建设 项目流程

From DataAccess standpoint, there is UnitOfWork Pattern (8921498.html)aggregates all entity repository, this is at a cost you need to create entity repository for every entity even they are predominately similiar in terms of CRUD operation,  consider in real application there are huge amount of entities need to be created, creating Repository for each of them is not worth the investment and is hard to maintain.

This give rise to GenericRepository pattern which take only one class to cater all major entity datastore CRUD needs, all it take is DBContext so the class can have access to every database table using the Dbset attributes.

For the specific query meet certain condition like join, paging, sorting,  GenericRepository has 2 methods (for returning single entity and list) taking a parameter with type of Specification,  Specification has a method call GenerateIQuerable which will take DbSet<T>'s queryable and attach the condition clause that translated from certain rules.

namespace ProductService.CommandHandlers
{public class NewProductCommandHandler : ICommandHandler<NewProductCommand>{private readonly IMessageBrokerFactory _messageBrokerFactory;private StoreDBContext _dbcontext;public NewProductCommandHandler(IMessageBrokerFactory messageBrokerFactory, StoreDBContext dbcontext          ){_messageBrokerFactory = messageBrokerFactory;_dbcontext = dbcontext;} public async Task  HandleAsync(NewProductCommand command, ICorrelationContext context){var repository = new GenericSqlServerRepository<Product, StoreDBContext>(_dbcontext);var spec = new ProductByNameSpec(command.Name);var existedwithName = await repository.GetEntityBySpec(spec);if (existedwithName == null){ await repository.AddModel(new Product(command.Id, command.Name, command.CategoryId, command.Price));await _messageBrokerFactory.Publisher.PublishAsync<ProductCreated>(new ProductCreated { Id = command.Id, Name = command.Name }, context);}else{await _messageBrokerFactory.Publisher.PublishAsync<RejectedEvent>(new RejectedEvent(command.Name + " already exists", command.Id.ToString()), context);}}
using Common.DataAccess;
using ProductService.Models;namespace ProductService.SQLiteDB
{public class ProductByProductIdSpec : BaseSpecification<Product>{public ProductByProductIdSpec(int Id) : base(e => e.Id == Id){}}public class ProductByNameSpec : BaseSpecification<Product>{public ProductByNameSpec(string productname) : base(e => e.Name == productname){ }}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;namespace Common.DataAccess
{public abstract class BaseSpecification<T> where T : class{public Expression<Func<T, bool>> Criteria { get; private set; }public Expression<Func<T, object>> Orderby { get; private set; }public Expression<Func<T, bool>> AscOrdered { get; private set; }public List<Expression<Func<T, object>>> IncludeList { get; set; } = new List<Expression<Func<T, object>>>();public BaseSpecification(Expression<Func<T, bool>> criteria){Criteria = criteria;}public void AddIncludes(Expression<Func<T, object>> includeItem ){IncludeList.Add(includeItem);}public IQueryable<T> GenerateIQuerable (IQueryable<T> queryable){if (Criteria != null)queryable = queryable.Where(Criteria);if (Orderby != null)queryable = queryable.OrderBy(Orderby);if (AscOrdered != null)queryable = queryable.OrderByDescending(AscOrdered);queryable = IncludeList.Aggregate(queryable, (current, includeitem) => (current.Include(includeitem)));return queryable;}}}
using Common.Model;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;namespace Common.DataAccess
{public class GenericSqlServerRepository<TEntity, TDbContext> where TDbContext:DbContextwhere TEntity:ModelBase{DbContext _dbcontext;public GenericSqlServerRepository(TDbContext dbcontext){_dbcontext = dbcontext;}public async Task AddModel(TEntity entity){_dbcontext.Set<TEntity>().Add(entity);await _dbcontext.SaveChangesAsync();}public async Task DeleteModel(TEntity entity){_dbcontext.Set<TEntity>().Remove(entity);await _dbcontext.SaveChangesAsync();}public async Task UpdateModel(TEntity entity){_dbcontext.Set<TEntity>().Update(entity);await _dbcontext.SaveChangesAsync();}public async Task<TEntity> FindByPrimaryKey(int id){return await _dbcontext.Set<TEntity>().FindAsync(id);}public async Task<TEntity> GetEntityBySpec(BaseSpecification<TEntity> spec){return await spec.GenerateIQuerable(_dbcontext.Set<TEntity>().AsQueryable<TEntity>()).FirstOrDefaultAsync();}public async Task<IReadOnlyList<TEntity>> GetEntityListBySpec(BaseSpecification<TEntity> spec){return await spec.GenerateIQuerable(_dbcontext.Set<TEntity>().AsQueryable<TEntity>()).ToListAsync();}}
}

 

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询