Как сопоставить dbcontext с фактическим dbcontext
Я создаю универсальные репозитории и универсальную единицу работы .когда я пытаюсь сохранить запись, но, к сожалению, запись не сохраняется и даже никакой ошибки не происходит.
Что я уже пробовал:
public interface IRepository<TEntity> where TEntity : class,new() { Task<IReadOnlyList<TEntity>> ListAllAsync(); Task AddAsync(TEntity entity); }
public class Repository<T> : IRepository<T> where T : class, new() { protected readonly DbContext _dbContext; public Repository(DbContext dbContext) { this._dbContext = dbContext; } public async Task AddAsync(T entity) { await _dbContext.Set<T>().AddAsync(entity); } public async Task<IReadOnlyList<T>> ListAllAsync() { return await _dbContext.Set<T>().AsNoTracking().ToListAsync(); } }
public interface IUnitOfWork : IDisposable { Task CompleteAsync(); }
public class UnitOfWork : IUnitOfWork { private readonly DbContext _dbContext; public UnitOfWork(DbContext dbContext) { _dbContext = dbContext; } public async Task CompleteAsync() { await _dbContext.SaveChangesAsync(); } public void Dispose() { _dbContext.Dispose(); } }
public class CustomerService : ICustomerService { private readonly IRepository<Customer> _customerRepository; private readonly IUnitOfWork _unitOfWork; public CustomerService(IRepository<Customer> customerRepository, IUnitOfWork unitOfWork) { this._customerRepository = customerRepository; this._unitOfWork = unitOfWork; } public async Task<IEnumerable<CustomerList>> ListAsync() { var customer = await _customerRepository.ListAllAsync(); List<CustomerList> customers = new List<CustomerList>(); foreach (var item in customer) { customers.Add(new CustomerList { Id = item.Id, Name = item.Name }); } return customers; } public async Task<CustomerResource> SaveAsync(CustomerResource category) { try { await _customerRepository.AddAsync(new Customer { Name = category.Name }); await _unitOfWork.CompleteAsync(); return new CustomerResource(true, "Successfully"); } catch (Exception ex) { return new CustomerResource($"An error occurred when saving the customer :{ex.Message}" ); } } }
services.AddScoped<DbContext, ApplicationDbContext>();
services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddScoped(typeof(IRepository<>), typeof(Repository<>));