Ahmed Dabas Ответов: 0

Сохранение данных не работает с autofac


Привет...
я работаю над приложением wpf (без шаблона Mvvm)
использование универсального репозитория и единицы работы, а также Autofac
проблема, с которой я сталкиваюсь , когда я сохраняю данные в базу данных, ничего не происходит (не сохранение)
я много чего пробую и ничего не получается
загрузите файл по этой ссылке
TimCoAutoFac[^]

Что я уже пробовал:

public class GenericRepository<T> : IGenericRepository<T> where T : class
    {
        private readonly DbContext _context;
        private readonly DbSet<T> _dbSet;
        private bool _disposed;

        public GenericRepository(DbContext context)
        {
            _context = context;
            _dbSet = _context.Set<T>();
        }

        public IQueryable<T> GetAll(Expression<Func<T, bool>> filter = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
            params Expression<Func<T, object>>[] includes)
        {
            var query = includes.Aggregate<Expression<Func<T, object>>, IQueryable<T>>(_dbSet,
                (current, include) => current.Include(include));

            if (filter != null)
                query = query.Where(filter);

            if (orderBy != null)
                query = orderBy(query);

            return query.AsNoTracking();
        }

        public async Task<List<T>> GetAllAsync(Expression<Func<T, bool>> filter = null,
            Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null,
            params Expression<Func<T, object>>[] includes)
        {
            IQueryable<T> query = _dbSet;

            foreach (var include in includes)
                query = query.Include(include);

            if (filter != null)
                query = query.Where(filter);

            if (orderBy != null)
                query = orderBy(query);

            return await query.AsNoTracking().ToListAsync();
        }

        public T GetById(int id)
        {
            return _context.Set<T>().Find(id);
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await _context.Set<T>().FindAsync(id);
        }

        public T Add(T t)
        {
            _context.Set<T>().Add(t);
            //_context.SaveChanges();
            return t;
        }

        public void AddRang(IEnumerable<T> t)
        {
            _context.Set<T>().AddRange(t);
            //_context.SaveChanges();
        }

        public T SingleOrDefault(Expression<Func<T, bool>> match)
        {
            return _context.Set<T>().SingleOrDefault(match);
        }

        public async Task<T> SingleOrDefaultAsync(Expression<Func<T, bool>> match)
        {
            return await _context.Set<T>().SingleOrDefaultAsync(match);
        }

        public ICollection<T> FindAll(Expression<Func<T, bool>> match)
        {
            return _context.Set<T>().Where(match).ToList();
        }

        public async Task<ICollection<T>> FindAllAsync(Expression<Func<T, bool>> match)
        {
            return await _context.Set<T>().Where(match).ToListAsync();
        }

        public void Delete(T entity)
        {
            _context.Set<T>().Remove(entity);
            //_context.SaveChanges();
        }

        public void DeleteById(int id)
        {
            var item = GetById(id);
            _context.Set<T>().Remove(item);
            //_context.SaveChanges();
        }

        public void DeleteRang(IEnumerable<T> entity)
        {
            _context.Set<T>().RemoveRange(entity);
            //_context.SaveChanges();
        }

        public T Update(T t, object key)
        {
            if (t == null)
                return null;
            var exist = _context.Set<T>().Find(key);
            if (exist != null) _context.Entry(exist).CurrentValues.SetValues(t);

            return exist;
        }

        public async Task<T> UpdateAsync(T t, object key)
        {
            if (t == null)
                return null;
            var exist = await _context.Set<T>().FindAsync(key);
            if (exist != null) _context.Entry(exist).CurrentValues.SetValues(t);

            return exist;
        }

        public int Count()
        {
            return _context.Set<T>().Count();
        }

        public async Task<int> CountAsync()
        {
            return await _context.Set<T>().CountAsync();
        }

        public bool Any(Expression<Func<T, bool>> filter)
        {
            return _context.Set<T>().Any(filter);
        }

        public async Task<bool> AnyAsync(Expression<Func<T, bool>> filter)
        {
            return await _context.Set<T>().AnyAsync(filter);
        }

        //public void Save()
        //{
        //    _context.SaveChanges();
        //}

        //public async Task<int> SaveAsync()
        //{
        //    return await _context.SaveChangesAsync();
        //}

        public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            var query = _context.Set<T>().Where(predicate);
            return query;
        }

        public async Task<ICollection<T>> FindByAsync(Expression<Func<T, bool>> predicate)
        {
            return await _context.Set<T>().Where(predicate).ToListAsync();
        }

        public IQueryable<T> GetAllIncluding(params Expression<Func<T, object>>[] includeProperties)
        {
            var queryable = GetAll().AsQueryable();

            return includeProperties.Aggregate(queryable,
                (current, includeProperty) => current.Include(includeProperty));
        }

        public string GenerateCode(string prefix)
        {
            return prefix + Guid.NewGuid().ToString("D").GetHashCode().ToString("X");
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing) _context.Dispose();
                _disposed = true;
            }
        }

    }



public class UnitOfWork : IUnitOfWork 
    {
        public DbContext Context { get; }
        private bool _disposed;


        public UnitOfWork(DbContext context)
        {
            Context = context;
        }

        public void Save()
        {
            Context.SaveChanges();
        }

        public async Task SaveAsync()
        {
            await Context.SaveChangesAsync();
            ////try
            //{
            //    await _context.SaveChangesAsync();

            //}
            //catch (DbEntityValidationException e)
            //{
            //    foreach (var eve in e.EntityValidationErrors)
            //    {
            //        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            //            eve.Entry.Entity.GetType().Name, eve.Entry.State);

            //        foreach (var ve in eve.ValidationErrors)
            //        {
            //            Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
            //                ve.PropertyName,
            //                eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
            //                ve.ErrorMessage);
            //        }
            //    }
            //    throw;
            //}
        }

        public virtual void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
                if (disposing)
                {
                    // dispose the db context.
                    Context.Dispose();
                }

            _disposed = true;
        }

        public DbContextTransaction DbContextTransaction()
        {
            return Context.Database.BeginTransaction();
        }

    }



public class AccountStatementService :  IAccountStatementService
    {
        public IGenericRepository<AccountStatement> AccountStatementRepository { get; }

        public AccountStatementService(IGenericRepository<AccountStatement> accountStatementRepository)
        {
            AccountStatementRepository = accountStatementRepository;
        }

        public AccountStatement VoucherAccountStatement(Voucher voucher , int? type)
        {
            return new AccountStatement()
            {
                EntryCode = voucher.VoucherCode,
                TheDate = voucher.TheDate,
                EmployeeId = voucher.EmployeeId,
                Debit = type == 2 ? voucher.VoucherAmount : 0,
                Credit = type == 1 ? voucher.VoucherAmount : 0,
                CurrencyId = voucher.CurrencyId,
                ExchangeRate = voucher.ExchangeRate,
                OperationId = voucher.OperationId,
                Details = voucher.Details,
                IsActive = true,
            };
        }

        public void Dispose()
        {
            AccountStatementRepository?.Dispose();
        }
    }


public static class ContainerConfig
 {
     public static IContainer Configure()
     {
         var connection =
             System.Configuration.ConfigurationManager.
                 ConnectionStrings["SalaryDbConnection"].ConnectionString;

         var builder = new ContainerBuilder();

         //builder
         //    .RegisterAssemblyTypes(Assembly.Load(nameof(Repository)))
         //    .AsClosedTypesOf(typeof(IGenericRepository<>));



         builder
             .RegisterGeneric(typeof(GenericRepository<>))
             .As(typeof(IGenericRepository<>))
             .InstancePerDependency();


         builder.RegisterType<SalaryDbContext>()
             .As<DbContext>()
             .WithParameter("connectionstring", connection)
             .InstancePerDependency();

         builder
             .RegisterType<UnitOfWork>()
             .As<IUnitOfWork>()
             .InstancePerDependency();


         builder
              .RegisterAssemblyTypes(Assembly.Load(nameof(UI)));


         builder
             .RegisterAssemblyTypes(Assembly.Load(nameof(Service)))
             .Where(t => t.Namespace != null && t.Namespace.Contains("Services"))
             .As(t => t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name));


         return builder.Build();
     }
 }



private readonly IVoucherService _voucherService;
        private readonly IEmployeeService _employeeService;
        private readonly IOperationService _operationService;
        private readonly ICurrencyService _currencyService;
        private readonly IAccountStatementService _accountStatementService;
        private readonly IUnitOfWork _unitOfWork;

        public PageVoucher(IVoucherService paymentVoucherService
            , IEmployeeService employeeService
            , IOperationService operationService
            , ICurrencyService currencyService
            , IAccountStatementService accountStatementService
            , IUnitOfWork unitOfWork)
        {
            InitializeComponent();
            _voucherService = paymentVoucherService;
            _employeeService = employeeService;
            _operationService = operationService;
            _currencyService = currencyService;
            _accountStatementService = accountStatementService;
            _unitOfWork = unitOfWork;
        }

voucherService.VoucherRepository.Add(item);
                _accountStatementService.AccountStatementRepository.Add(accountStatement);
                await _unitOfWork.SaveAsync();

Gerry Schmitz

Вы начинаете с того, что работает, а затем делаете его "универсальным". Вы прокомментировали кучу сохранений, затем добавили несколько новых, и не похоже, что вы звоните кому-то из них. Это выглядело как "не исправляй, я не сломан".

0 Ответов