Click here to Skip to main content
15,887,474 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ...
i'm working on wpf app (without Mvvm Pattern)
using Generic Repository and Unit Of Work and Autofac
the problem that i face, when i save data to database , nothing happen (not saving)
i try alot of things and nothing working
the file uploded at this link
TimCoAutoFac[^]

What I have tried:

C#
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;
            }
        }

    }



C#
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();
        }

    }



C#
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();
        }
    }


C#
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();
     }
 }



C#
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();
Posted
Comments
[no name] 2-Feb-20 12:20pm    
You start with one that works, then you make it "generic". You commented out a bunch of saves, then added some new ones, and don't look like you're calling any of them. This looked like a don't fix I'm not broken.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900