public void TestCustomerCreation()
        {
            //Creating customer

            var Customer = new Customer() { CustomerName = "Customer 1", Telephome = "78-676-121212", Sites = new List<Site>() };
            Customer.Sites.Add(new Site() { Address = "Site 1", PostCode = "001", SiteNumber = "ST01" });
            Customer.Sites.Add(new Site() { Address = "Site 2", PostCode = "002", SiteNumber = "ST02" });

            iocCtxFactory = iocContainer.Resolve<IDbContextFactory>();
            var iocDBContext = iocCtxFactory.GetContext();

            //adding customer to database
            var sotredCustomer = iocDBContext.Set<Customer>().Add(Customer);
            iocDBContext.SaveChanges();
            var customerId = sotredCustomer.Id;

            //Test
            var nonIoCContext = new DbContextFactory().GetContext();

            var customerFrom_IOC_Context = iocCtxFactory.GetContext().Set<Customer>().Where(c => c.Id == customerId).SingleOrDefault();

            var customerNon_IOC_Context = nonIoCContext.Set<Customer>().Where(c => c.Id == customerId).SingleOrDefault();

            Assert.IsNull(customerNon_IOC_Context.Sites);

            //Expecting empty but having values if IOC lifestyle is singleton or PerWebRequest :(
            //transient is working as expected
            Assert.IsNull(customerFrom_IOC_Context.Sites);
        }
        public async Task <ProductModel> GetProduct(int id)
        {
            using (var context = _contextFactory.GetContext())
            {
                Product product = await context.GetProduct(id);

                return(MapProductToDto(product));
            }
        }
        public override async Task <TAggregate> GetByIdAsync(TKey id)
        {
            // TODO: Patch aggregate on all entities
            var type = typeof(TAggregate);

            using (var ctx = _contextFactory.GetContext())
            {
                var paths = _navigationPaths.GetOrAdd(type.Name, typeName => GetIncludePaths(ctx, typeof(TAggregate)));
                return(await Include(ctx.Set <TAggregate>().AsNoTracking(), paths).FirstOrDefaultAsync(o => o.Id.Equals(id)).ConfigureAwait(false));
            }
        }
Beispiel #4
0
 public UnitOfWork(IDbContextFactory <APPDbContext> dbContextFactory, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
 {
     _dbContext                        = dbContextFactory.GetContext();
     UserRepository                    = new UserRepository(_dbContext);
     AccountsRepository                = new AccountsRepository(_dbContext);
     Account_RolesRepository           = new Account_RolesRepository(_dbContext);
     RolesRepository                   = new RolesRepository(_dbContext);
     PermissionsRepository             = new PermissionsRepository(_dbContext);
     EmployeesRepository               = new EmployeesRepository(_dbContext);
     MenusRepository                   = new MenusRepository(_dbContext);
     JobPositionsRepository            = new JobPositionsRepository(_dbContext);
     MotorManufactureRepository        = new MotorManufactureRepository(_dbContext);
     MotorTypesRepository              = new MotorTypesRepository(_dbContext);
     ServicesRepository                = new ServicesRepository(_dbContext);
     MotorLiftsRepository              = new MotorLiftsRepository(_dbContext);
     SupplierRepository                = new SupplierRepository(_dbContext);
     CustomersRepository               = new CustomersRepository(_dbContext);
     AccessoriesRepository             = new AccessoriesRepository(_dbContext);
     TemporaryBill_ServiceRepository   = new TemporaryBill_ServiceRepository(_dbContext);
     TemporaryBillRepository           = new TemporaryBillRepository(_dbContext);
     TemporaryBill_AccesaryRepository  = new TemporaryBill_AccesaryRepository(_dbContext);
     ImportReceiptRepository           = new ImportReceiptRepository(_dbContext);
     ImportReceipt_AccessoryRepository = new ImportReceipt_AccessoryRepository(_dbContext);
     ServicePriceHistoryRepository     = new ServicePriceHistoryRepository(_dbContext);
     AccessoryPriceHistoryRepository   = new AccessoryPriceHistoryRepository(_dbContext);
 }
Beispiel #5
0
 public UnitOfWork(IDbContextFactory <APPDbContext> dbContextFactory, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
 {
     _dbContext                     = dbContextFactory.GetContext();
     UserRepository                 = new UserRepository(_dbContext);
     MenuRepository                 = new MenuRepository(_dbContext);
     RolesRepository                = new RolesRepository(_dbContext);
     Role_PermissionsRepository     = new Role_PermissionsRepository(_dbContext);
     AccountsRepository             = new AccountsRepository(_dbContext);
     AccountRolesRepository         = new AccountRolesRepository(_dbContext);
     CategoryRepository             = new CategoryRepository(_dbContext);
     Content_CategoriesRepository   = new Content_CategoriesRepository(_dbContext);
     AuthorsRepository              = new AuthorsRepository(_dbContext);
     GroupsRepository               = new GroupsRepository(_dbContext);
     NewsSourcesRepository          = new NewsSourcesRepository(_dbContext);
     TypesRepository                = new TypesRepository(_dbContext);
     ContentTypesRepository         = new ContentTypesRepository(_dbContext);
     Content_GroupsRepository       = new Content_GroupsRepository(_dbContext);
     TitleImagesRepository          = new TitleImagesRepository(_dbContext);
     MediasRepository               = new MediasRepository(_dbContext);
     ContentsRepository             = new ContentsRepository(_dbContext);
     QuanLyDonGiaNhuanButRepository = new QuanLyDonGiaNhuanButRepository(_dbContext);
     TheLoai_HeSoRepository         = new TheLoai_HeSoRepository(_dbContext);
     NhuanButRepository             = new NhuanButRepository(_dbContext);
     ContactRepository              = new ContactRepository(_dbContext);
 }
Beispiel #6
0
 public FrequencyRepository(
     IFrequencyAdapter adapter,
     IDbContextFactory dbContextFactory)
 {
     _adapter = adapter;
     _context = (WebFrequenciesDbContext)dbContextFactory.GetContext();
 }
Beispiel #7
0
 public UnitOfWork(IDbContextFactory <smartFundsDbContext> dbContextFactory, IOptions <smartFundsRedisOptions> redisConfigurationOptions
                   , IRedisAutoCompleteProvider redisAutoCompleteProvider, IHttpContextAccessor httpContextAccessor)
 {
     _context = dbContextFactory.GetContext();
     _redisConfigurationOptions = redisConfigurationOptions;
     _redisAutoCompleteProvider = redisAutoCompleteProvider;
     _httpContextAccessor       = httpContextAccessor;
 }
Beispiel #8
0
 public async Task <ICollection <Book> > Get()
 {
     using (var context = _contextFactory.GetContext())
     {
         return(await context.Books.ToListAsync());
     }
 }
 public void UnitTestSetup()
 {
     _fakeAppToDbModelConverter = Substitute.For <IAppToDbModelConverter>();
     _fakeDbToAppModelConverter = Substitute.For <IDbToAppModelConverter>();
     _fakeDbContextFactory      = Substitute.For <IDbContextFactory>();
     _fakeDbContext             = Substitute.For <IAppDbContext>();
     _fakeDbContextFactory.GetContext().Returns(_fakeDbContext);
     _uut = new RealDatabaseQuerier(_fakeDbContextFactory, _fakeDbToAppModelConverter, _fakeAppToDbModelConverter);
 }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the class UnitOfWork.
        /// </summary>
        /// <param name="context">Database context</param>
        public EFUnitOfWork(IDbContextFactory contextFactory)
        {
            this.dbContext = contextFactory.GetContext();

            if (this.dbContext == null)
            {
                throw new ArgumentNullException("context");
            }
        }
Beispiel #11
0
        public UnitOfWork([NotNull] IDbContextFactory factory)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            _context          = factory.GetContext();
            _dbContextFactory = factory;
        }
 public void Init()
 {
     using (var context = _smartFundsDbContextFactory.GetContext())
     {
         if (context.Database.EnsureDeleted())
         {
             context.Database.Migrate();
             context.EnsureSeeded();
         }
     }
 }
Beispiel #13
0
        public UnitOfWork(IDbContextFactory <KhaoSatDbContext> dbContextFactory, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            _dbContext = dbContextFactory.GetContext();

            UserAnswersRepository = new UserAnswersRepository(_dbContext);
            UserRepository        = new UserRepository(_dbContext);
            UserSurveysRepository = new UserSurveysRepository(_dbContext);
            SurveysRepository     = new SurveyRepository(_dbContext);
            AnswerRepository      = new AnswerRepository(_dbContext);
            QuestionsRepository   = new QuestionsRepository(_dbContext);
        }
 public void TestSetup()
 {
     _fakeDbContext             = Substitute.For <IAppDbContext>();
     _fakeDbToAppModelConverter = Substitute.For <IDbToAppModelConverter>();
     _converterToIntegrate      = new ApptoDbModelConverter();
     _dbContextFactory          = Substitute.For <IDbContextFactory>();
     _dbContextFactory.GetContext().Returns(_fakeDbContext);
     _dbQuerier = new RealDatabaseQuerier(_dbContextFactory,
                                          _fakeDbToAppModelConverter,
                                          _converterToIntegrate);
 }
 public void Init()
 {
     using (var context = _smartFundsDbContextFactory.GetContext())
     {
         if (!context.AllMigrationsApplied())
         {
             context.Database.Migrate();
         }
         context.EnsureSeeded();
     }
 }
        public void TestCustomerCreation()
        {
            //Creating customer


            var Customer = new Customer()
            {
                CustomerName = "Customer 1", Telephome = "78-676-121212", Sites = new List <Site>()
            };

            Customer.Sites.Add(new Site()
            {
                Address = "Site 1", PostCode = "001", SiteNumber = "ST01"
            });
            Customer.Sites.Add(new Site()
            {
                Address = "Site 2", PostCode = "002", SiteNumber = "ST02"
            });

            iocCtxFactory = iocContainer.Resolve <IDbContextFactory>();
            var iocDBContext = iocCtxFactory.GetContext();

            //adding customer to database
            var sotredCustomer = iocDBContext.Set <Customer>().Add(Customer);

            iocDBContext.SaveChanges();
            var customerId = sotredCustomer.Id;

            //Test
            var nonIoCContext = new DbContextFactory().GetContext();

            var customerFrom_IOC_Context = iocCtxFactory.GetContext().Set <Customer>().Where(c => c.Id == customerId).SingleOrDefault();

            var customerNon_IOC_Context = nonIoCContext.Set <Customer>().Where(c => c.Id == customerId).SingleOrDefault();

            Assert.IsNull(customerNon_IOC_Context.Sites);

            //Expecting empty but having values if IOC lifestyle is singleton or PerWebRequest :(
            //transient is working as expected
            Assert.IsNull(customerFrom_IOC_Context.Sites);
        }
Beispiel #17
0
 public UnitOfWork(IDbContextFactory <DoAnDbContext> dbContextFactory, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
 {//2
     _dbContext = dbContextFactory.GetContext();
     DanhSachPhongRepository   = new DanhSachPhongRepository(_dbContext);
     DuThuyenRepository        = new DuThuyenRepository(_dbContext);
     HangPhongRepository       = new HangPhongRepository(_dbContext);
     KhachHangRepository       = new KhachHangRepository(_dbContext);
     KieuGiuongRepository      = new KieuGiuongRepository(_dbContext);
     NhomPhongRepository       = new NhomPhongRepository(_dbContext);
     PhieuDatChiTietRepository = new PhieuDatChiTietRepository(_dbContext);
     PhieuDatPhongRepository   = new PhieuDatPhongRepository(_dbContext);
 }
        public void Rollback()
        {
            var dbContext = _dbContextFactory.GetContext();

            foreach (var dbEntityEntry in dbContext.ChangeTracker.Entries())
            {
                if (dbEntityEntry.Entity != null)
                {
                    dbEntityEntry.State = EntityState.Detached;
                }
            }
        }
Beispiel #19
0
        public UnitOfWork(IDbContextFactory dbContextFactory, IRequestContextProvider httpRequestProvider)
        {
            _dbContextManager = dbContextFactory.GetContext();

            var userName = httpRequestProvider.Context.UserName;

            _dbContextManager.ChangeTracker.Tracked += (obj, arg) =>
            {
                var state  = arg.Entry.State;
                var entity = arg.Entry.Entity;

                if (state != EntityState.Added)
                {
                    return;
                }

                if (entity is BaseEntity baseEntity)
                {
                    baseEntity.Id = Guid.NewGuid();
                }

                var currentDateTime = DateTime.UtcNow;

                if (entity is AuditCreationEntity auditCreationEntity)
                {
                    auditCreationEntity.CreatedAt = currentDateTime;
                    auditCreationEntity.CreatedBy = userName;
                }

                if (!(entity is AuditEntity auditEntity))
                {
                    return;
                }

                auditEntity.ModifiedAt = currentDateTime;
                auditEntity.ModifiedBy = userName;
            };

            _dbContextManager.ChangeTracker.StateChanged += (obj, arg) =>
            {
                var state  = arg.Entry.State;
                var entity = arg.Entry.Entity;

                if (state != EntityState.Modified || !(entity is AuditEntity auditEntity))
                {
                    return;
                }

                auditEntity.ModifiedAt = DateTime.UtcNow;
                auditEntity.ModifiedBy = userName;
            };
        }
Beispiel #20
0
        public EventLogger(IDbContextFactory dbContextFactory)
        {
            var dbContext = dbContextFactory.GetContext();
            _dbPackageEventSet = dbContext.Set<PackageEvent>();
            _dbSchedulerEventSet = dbContext.Set<SchedulerEvent>();
            _dbServerEventSet = dbContext.Set<ServerEvent>();
            _dbSystemEventSet = dbContext.Set<SystemEvent>();
            _dbServerDeploymentEventSet = dbContext.Set<ServerDeploymentEvent>();
            _dbNotificationSet = dbContext.Set<Notification>();
            _dbNotificationTypeSet = dbContext.Set<NotificationType>();

            intNotificationTypeID = FindNotificationType("MindAlign");
        }
Beispiel #21
0
 public LinqRepository(IDbContextFactory dbContextFactory)
 {
     try
     {
         if (dbContextFactory == null)
         {
             throw new NullReferenceException("dbContextFactory不得为null");
         }
         db = dbContextFactory.GetContext() as DataContext;
     }
     catch (Exception ex)
     {
         throw new RepositoryException(string.Format("创建实体({0})的仓储对象出错", EType.Name), ex);
     }
 }
Beispiel #22
0
        public Task <bool> LoadFile(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("Invalid argument");
            }

            if (!File.Exists(filePath))
            {
                throw new Exception("File not exist!" + filePath);
            }

            return(Task <bool> .Factory.StartNew(() =>
            {
                Logger.Logger.Log(" Begin load : " + filePath);
                using (var context = _factoryContext.GetContext())
                {
//					context.Configuration.AutoDetectChangesEnabled = false;
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        try
                        {
                            Logger.Logger.Log("Begin read");
                            FormatHeader header = LoadHeader(context, filePath);
                            foreach (var line in GetLine(filePath))
                            {
                                FormatLine formatLine = ParseLine(line);
                                Logger.Logger.Log("\tread line");
                                LoadData(context, header, formatLine);
                                _cancellationToken.ThrowIfCancellationRequested();
                            }
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            transaction.Rollback();
                            Logger.Logger.Log("---------ROLLBACK!!");
                            Logger.Logger.Log("Processing: " + filePath + " interupted from ", this.GetType(), e);
                            throw e;
                        }
                    }
                }

                Logger.Logger.Log(" Load successfully");
                return true;
            }));
        }
 public void BeforeTest()
 {
     Database.SetInitializer(new DropCreateDatabaseAlways<EasyReadDbContext>());
     _contextFactory = new TestContextFactory(new EasyReadDbContext("DefaultContext"));
     _contextFactory.GetContext().Database.Initialize(true);
 }
Beispiel #24
0
 public Repo(IDbContextFactory f)
 {
     c = f.GetContext();
 }
Beispiel #25
0
 public Repo(IDbContextFactory dbContextFactory)
 {
     DbContext = dbContextFactory.GetContext();
 }
Beispiel #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnitOfWork{TDbContext}"/> class.
 /// </summary>
 /// <param name="dbContextFactory">The database context factory.</param>
 public UnitOfWork(IDbContextFactory <TDbContext> dbContextFactory)
 {
     _dbContext = dbContextFactory.GetContext();
 }
Beispiel #27
0
        //private readonly ILog _log = LogManager.GetLogger("Security.Sample.Service");

        public UnitOfWork(IDbContextFactory factory)
        {
            _context = factory.GetContext();
        }
Beispiel #28
0
 public RepositoryBase(IDbContextFactory contextFactory)
 {
     _dbContext = contextFactory.GetContext();
 }
 public PostsRepository(IDbContextFactory dbContextFactory)
 {
     DbContext = dbContextFactory.GetContext();
     DbSet = DbContext.Set<Post>();
 }
Beispiel #30
0
 public UnitOfWork(IDbContextFactory dbContextFactory)
 {
     _dbContext = dbContextFactory.GetContext();
 }
 public UniRepo(IDbContextFactory a)
 {
     c = a.GetContext();
 }
Beispiel #32
0
        /// <summary>
        /// <para>This is typically used to create queries with custom projections. For example, you may wish</para>
        /// <para>to select only a small number of columns from the table.</para>
        /// </summary>
        /// <returns>An instance of IRepositoryConnectionlt;TEntity&gt;</returns>
        public virtual IRepositoryConnection <TEntity> OpenConnection()
        {
            var context = contextFactory.GetContext();

            return(new EntityFrameworkRepositoryConnection <TEntity>(context, true));
        }
Beispiel #33
0
 public UnitOfWork(IDbContextFactory <APPDbContext> dbContextFactory, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
 {
     _dbContext     = dbContextFactory.GetContext();
     UserRepository = new UserRepository(_dbContext);
 }
 public CategoriesRepository(IDbContextFactory dbContextFactory)
 {
     DbContext = dbContextFactory.GetContext();
     DbSet = DbContext.Set<Category>();
 }
Beispiel #35
0
 public PostRepository(IDbContextFactory contextFactory)
 {
     _context = contextFactory.GetContext();
 }
Beispiel #36
0
 public UnitOfWork(IDbContextFactory contextFactory)
 {
     Context = contextFactory.GetContext();
 }
Beispiel #37
0
 public UsageLogger(IDbContextFactory dbContextFactory)
 {
     var dbContext = dbContextFactory.GetContext();
     _dbUsageSet = dbContext.Set<Usage>();
 }
Beispiel #38
0
 public UserCredential(IDbContextFactory dbContextFactory)
 {
     var dbContext = dbContextFactory.GetContext();
     _dbAdGroupSet = dbContext.Set<ADGroup>();
 }
Beispiel #39
0
 public void Begin()
 {
     _contextFactory.GetContext();
 }