Ejemplo n.º 1
0
 public IReadOnlyList <T> FindMany <T>(Expression <Func <T, bool> > filter)
     where T : class
 {
     using (var context = new EntityFrameworkDbContext()) {
         return(context.Set <T>().Where(filter).ToList());
     }
 }
Ejemplo n.º 2
0
 public T QueryOne <T>(Expression <Func <T, bool> > filter)
     where T : class
 {
     using (var context = new EntityFrameworkDbContext()) {
         return(context.Set <T>().SingleOrDefault(filter));
     }
 }
Ejemplo n.º 3
0
        public TEntity Add(TEntity entity)
        {
            entity.Created = DateTime.UtcNow;
            TEntity addedEntity = DbSet.Add(entity);

            EntityFrameworkDbContext.SaveChanges();
            return(addedEntity);
        }
Ejemplo n.º 4
0
 public void InserMany <T>(IEnumerable <T> entities)
     where T : class
 {
     using (var context = new EntityFrameworkDbContext()) {
         context.Set <T>().AddRange(entities);
         context.SaveChanges();
     }
 }
Ejemplo n.º 5
0
 public void InsertOne <T>(T entity)
     where T : class
 {
     using (var context = new EntityFrameworkDbContext()) {
         context.Set <T>().Add(entity);
         context.SaveChanges();
     }
 }
Ejemplo n.º 6
0
        public async Task <IActionResult> Index()
        {
            using (var context = new EntityFrameworkDbContext())
            {
                var model = await context.Authors.AsNoTracking().ToListAsync();

                return(View(model));
            }
        }
Ejemplo n.º 7
0
        public virtual void Update(TEntity entity, bool save = true)
        {
            DbSet.Attach(entity);
            EntityFrameworkDbContext.Entry(entity).State = EntityState.Modified;

            if (save)
            {
                EntityFrameworkDbContext.SaveChanges();
            }
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Create([Bind("FirstName, LastName")] Author author)
        {
            using (var context = new EntityFrameworkDbContext())
            {
                context.Add(author);
                await context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Create([Bind("Title, AuthorId")] Book book)
        {
            using (var context = new EntityFrameworkDbContext())
            {
                context.Books.Add(book);
                await context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
        }
Ejemplo n.º 10
0
 private static void CreateFtpUsers(int count, string login)
 {
     using var context = new EntityFrameworkDbContext();
     context.FtpUsers.AddRange(Enumerable.Range(0, count).Select(_ => new FtpUser
     {
         Login = login,
         BoxId = Guid.NewGuid().ToString(),
         Id    = Guid.NewGuid(),
     }));
     context.SaveChanges();
 }
Ejemplo n.º 11
0
        private static UsersTable[] GenerateRandomUsersAndAssertCount(int count)
        {
            var scopeId = Guid.NewGuid().ToString();
            var users   = Enumerable.Range(0, count).Select(_ => GetRandomUser(scopeId, $"{Guid.NewGuid()}@gmail.com")).ToArray();

            using var context = new EntityFrameworkDbContext();
            context.Users.AddRange(users);
            context.SaveChanges();

            Assert.That(() => GetUserObjectsCount(scopeId, count), Is.EqualTo(count).After(180000, 1000));
            return(users);
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> Create()
        {
            using (var context = new EntityFrameworkDbContext())
            {
                var authors = await context.Authors.Select(a => new SelectListItem {
                    Value = a.AuthorId.ToString(),
                    Text  = $"{a.FirstName} {a.LastName}"
                }).ToListAsync();

                ViewBag.Authors = authors;
            }
            return(View());
        }
Ejemplo n.º 13
0
        private static void TextMethod()
        {
            using (var db = new EntityFrameworkDbContext())
            {
                var user = db.Users.First(name => name.NickName == "Marcello");

                foreach (var friend in user.RequestedFriendships)
                {
                    Console.WriteLine(user == friend.User1 ? friend.User2.NickName : friend.User1.NickName);
                }
                Console.WriteLine("_____________________________________________________");
                foreach (var friend in user.AcceptedFriendships)
                {
                    Console.WriteLine(user == friend.User1 ? friend.User2.NickName : friend.User1.NickName);
                }
            }
        }
Ejemplo n.º 14
0
        private FtpUser CreateFtpUser()
        {
            using var context = new EntityFrameworkDbContext();

            var userId  = Guid.NewGuid();
            var ftpUser = new FtpUser
            {
                Login = Guid.NewGuid().ToString(),
                BoxId = Guid.NewGuid().ToString(),
                Id    = userId,
            };

            context.FtpUsers.Add(ftpUser);
            context.SaveChanges();

            Assert.That(GetFtpUser(userId), Is.Not.Null, "Failed to create ftp user");
            return(ftpUser);
        }
Ejemplo n.º 15
0
        public void TestAllowSort()
        {
            using (var context = new EntityFrameworkDbContext())
            {
                var serializer = new Serializer(new AllPropertiesExtractor());
                var customer   = new Customer {
                    Age = 1, Name = "13"
                };
                context.Tests.Add(new TestTable
                {
                    Id                 = 1,
                    CompositeKey       = Guid.NewGuid().ToString(),
                    String             = "123",
                    Customer           = customer,
                    CustomerSerialized = serializer.Serialize(customer),
                });
                context.Users.Add(new UsersTable
                {
                    Email      = "123",
                    Id         = Guid.NewGuid(),
                    Patronymic = "1",
                    Surname    = "2",
                    FirstName  = "3",
                    ScopeId    = "scopeId",
                });
                context.SaveChanges();
            }

            using var browser = new BrowserForTests();

            var usersPage = browser.LoginAsSuperUser().SwitchTo <BusinessObjectTablePage>("UsersTable");

            usersPage = browser.RefreshUntil(usersPage, x => x.BusinessObjectItems.IsPresent.Get());
            usersPage.TableHeader.WaitPresence();
            usersPage.TableHeader.SortByColumn("Header_Id");

            var largeObjectPage = browser.SwitchTo <BusinessObjectTablePage>("TestTable");

            largeObjectPage = browser.RefreshUntil(largeObjectPage, x => x.BusinessObjectItems.IsPresent.Get());
            largeObjectPage.TableHeader.WaitPresence();
            largeObjectPage.TableHeader.WaitNotSortable("Header_Index");
            largeObjectPage.TableHeader.WaitNotSortable("Header_String");
            largeObjectPage.TableHeader.WaitNotSortable("Header_DateTime");
        }
Ejemplo n.º 16
0
        public void Test_DoubleTest_InsertToDatabase()
        {
            var configuration = new EntitySetupConfiguration();

            // const string connectionString = "Data Source=(local); Database=easyERP_test; User ID=sa; Password=; MultipleActiveResultSets=True";
            // EntityFrameworkDbContext dbContext = new EntityFrameworkDbContext(connectionString, configuration);
            // DbConnection dbConnection = new SqlConnection();
            var dbContext = new EntityFrameworkDbContext("easyERP_test");

            IUnitOfWork unitOfWork     = new EntityFrameworkUnitOfWork(dbContext);
            var         testRepository = new EntityFrameworkRepository <TestDoubles>(dbContext, unitOfWork);
            var         testModel      = new TestDoubles
            {
                Name = "test description"
            };

            testRepository.Add(testModel);
            unitOfWork.Commit();
        }
Ejemplo n.º 17
0
        private static void CreateUsers(int count, string scopeId, Guid?id = null)
        {
            if (count > 1 && id != null)
            {
                throw new InvalidOperationException();
            }

            using var context = new EntityFrameworkDbContext();
            context.Users.AddRange(Enumerable.Range(0, count).Select(_ => new UsersTable
            {
                Id         = id ?? Guid.NewGuid(),
                ScopeId    = scopeId,
                Email      = "*****@*****.**",
                FirstName  = "1",
                Surname    = "2",
                Patronymic = "3",
            }));
            context.SaveChanges();
        }
        public async Task Test()
        {
            var serializer = new Serializer(new AllPropertiesExtractor());
            var customer   = new Customer
            {
                Age    = 1,
                Name   = "qwer",
                Orders = new[]
                {
                    new Order {
                        Price = 3, ShippingAddress = "4"
                    },
                    new Order {
                        Price = 1, ShippingAddress = "2"
                    },
                }
            };

            await using var context = new EntityFrameworkDbContext();
            await context.Set <TestTable>().AddAsync(new TestTable
            {
                Id                 = 1,
                CompositeKey       = "2",
                Boolean            = false,
                Integer            = 1345,
                String             = "qwerty",
                DateTime           = DateTime.Today,
                DateTimeOffset     = DateTimeOffset.UtcNow,
                Customer           = customer,
                CustomerSerialized = serializer.Serialize(customer),
            });

            await context.Set <UsersTable>().AddAsync(new UsersTable
            {
                Id    = 1,
                Email = "2",
                Name  = "3",
            });

            await context.SaveChangesAsync();
        }
Ejemplo n.º 19
0
        public int UpdatePricesInMainCurrency()
        {
            Currency mainCurrency = EntityFrameworkDbContext.Currencies.SingleOrDefault(x => !x.IsDeleted && x.IsMain);

            if (mainCurrency == null)
            {
                throw new ArgumentNullException("There is no main currency in the system!");
            }
            var productsWithCurrencyRate = from product in DbSet
                                           join cr in
                                           (from currencyRate in EntityFrameworkDbContext.CurrencyRates
                                            where currencyRate.DateOfRate ==
                                            (from currencyRate1 in EntityFrameworkDbContext.CurrencyRates select currencyRate1).Max(currencyRate1 => currencyRate1.DateOfRate)
                                            select currencyRate) on product.CurrencyIdOfThePrice equals cr.CurrencyId
                                           select new { Product = product, CurrencyRate = cr };

            productsWithCurrencyRate.ToList().ForEach(x =>
            {
                x.Product.PriceInTheMainCurrency = x.Product.Price * x.CurrencyRate.Rate;
                Update(x.Product, false);
            });
            return(EntityFrameworkDbContext.SaveChanges());
        }
Ejemplo n.º 20
0
        public int UserInfoUpdate(UserInfoRequestModel request)
        {
            EntityFrameworkDbContext _db = new EntityFrameworkDbContext();
            //修改需要对主键赋值,注意:这里需要对所有字段赋值,没有赋值的字段会用NULL更新到数据库
            var user = new UserInfoResponseModel
            {
                UID       = request.UID,
                UserNO    = request.UserNO,
                UserName  = request.UserName,
                UserEmail = request.UserEmail,
                PassWord  = request.NewPassWord
            };

            //将实体附加到对象管理器中
            _db.UserInfo.Attach(user);

            //获取到状态实体,可以修改其状态
            var setEntry = ((IObjectContextAdapter)_db).ObjectContext.ObjectStateManager.GetObjectStateEntry(user);

            //只修改实体属性
            setEntry.SetModifiedProperty("PassWord");

            return(_db.SaveChanges());
        }
Ejemplo n.º 21
0
        public IQueryable <TEntity> Get(Expression <Func <TEntity, bool> > filter = null, Func <IQueryable <TEntity>, IOrderedQueryable <TEntity> > orderBy = null, string includeProperties = "")
        {
            IQueryable <TEntity> query = EntityFrameworkDbContext.Set <TEntity>();

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

            if (!string.IsNullOrWhiteSpace(includeProperties))
            {
                foreach (var includeProperty in includeProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    query = query.Include(includeProperty);
                }
            }

            if (orderBy != null)
            {
                return(orderBy(query).AsQueryable());
            }

            return(query.AsQueryable());
        }
Ejemplo n.º 22
0
 public OrdersRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext)
 {
 }
Ejemplo n.º 23
0
 public CountriesRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext)
 {
 }
Ejemplo n.º 24
0
 private static int GetUserObjectsCount(string scopeId, int limit)
 {
     using var context = new EntityFrameworkDbContext();
     return(context.Users.Where(x => x.ScopeId == scopeId).Take(limit + 1).Count());
 }
Ejemplo n.º 25
0
 public virtual void Delete(params TEntity[] entities)
 {
     DbSet.RemoveRange(entities);
     EntityFrameworkDbContext.SaveChanges();
 }
Ejemplo n.º 26
0
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            //HTTP context and other related stuff
            builder.Register(c => new HttpContextWrapper(HttpContext.Current) as HttpContextBase)
            .As <HttpContextBase>()
            .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve <HttpContextBase>().Request)
            .As <HttpRequestBase>()
            .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve <HttpContextBase>().Response)
            .As <HttpResponseBase>()
            .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve <HttpContextBase>().Server)
            .As <HttpServerUtilityBase>()
            .InstancePerLifetimeScope();
            builder.Register(c => c.Resolve <HttpContextBase>().Session)
            .As <HttpSessionStateBase>()
            .InstancePerLifetimeScope();

            builder.RegisterInstance(new AreaSettings()).AsSelf();

            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

            //user agent helper
            builder.RegisterType <UserAgentHelper>().As <IUserAgentHelper>().InstancePerLifetimeScope();

            //controllers
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());

            //data layer
            const string ConnectionString = "easyerp_db";
            var          dataContext      = new EntityFrameworkDbContext(ConnectionString);

            builder.Register(d => new EntityFrameworkDbContext("easyerp_db")).AsSelf().As <IEntityFrameworkDbContext>()
            .InstancePerLifetimeScope();

            builder.RegisterType <EntityFrameworkUnitOfWork>().As <IUnitOfWork>().InstancePerLifetimeScope();

            builder.RegisterGeneric(typeof(EntityFrameworkRepository <>))
            .As(typeof(IRepository <>))
            .InstancePerLifetimeScope();

            //work context
            builder.RegisterType <WebWorkContext>().As <IWorkContext>().InstancePerLifetimeScope();

            // Services
            builder.RegisterType <EmployeeService>().As <IEmployeeService>().InstancePerLifetimeScope();
            builder.RegisterType <ConsumptionService>().As <IConsumptionService>().InstancePerLifetimeScope();
            builder.RegisterType <EmployeeTimesheetService>()
            .As <ITimesheetService <WorkTimeStatistic> >()
            .InstancePerLifetimeScope();
            builder.RegisterType <ConsumptionTimesheetService>()
            .As <ITimesheetService <ConsumptionStatistic> >()
            .InstancePerLifetimeScope();
            builder.RegisterType <CustomerService>().As <ICustomerService>().InstancePerLifetimeScope();
            builder.RegisterType <StoreSaleService>().As <IStoreSaleService>().InstancePerLifetimeScope();
            builder.RegisterType <PostRetailService>().As <IPostRetailService>().InstancePerLifetimeScope();

            builder.RegisterType <CategoryService>().As <ICategoryService>().InstancePerLifetimeScope();
            builder.RegisterType <InventoryService>().As <IInventoryService>().InstancePerLifetimeScope();
            builder.RegisterType <PaymentService>().As <IPaymentService>().InstancePerLifetimeScope();
            builder.RegisterType <ProductService>().As <IProductService>().InstancePerLifetimeScope();
            builder.RegisterType <OrderService>().As <IOrderService>().InstancePerLifetimeScope();

            builder.RegisterType <UserService>().As <IUserService>().InstancePerLifetimeScope();
            builder.RegisterType <EncryptionService>().As <IEncryptionService>().InstancePerLifetimeScope();
            builder.RegisterType <StandardPermissionProvider>().As <IPermissionProvider>().InstancePerLifetimeScope();
            builder.RegisterType <ProductPriceService>().As <IProductPriceService>().InstancePerLifetimeScope();
            builder.RegisterType <PermissionService>().As <IPermissionService>().InstancePerLifetimeScope();
            builder.RegisterType <AclService>().As <IAclService>().InstancePerLifetimeScope();

            builder.RegisterType <StoreService>().As <IStoreService>().InstancePerLifetimeScope();
            builder.RegisterType <ExportManager>().As <IExportManager>().InstancePerLifetimeScope();

            builder.RegisterType <FormsAuthenticationService>().As <IAuthenticationService>().InstancePerLifetimeScope();

            builder.RegisterType <DateTimeHelper>().As <IDateTimeHelper>().InstancePerLifetimeScope();
            builder.RegisterType <PageHeadBuilder>().As <IPageHeadBuilder>().InstancePerLifetimeScope();
            builder.RegisterType <RoutePublisher>().As <IRoutePublisher>().SingleInstance();
        }
Ejemplo n.º 27
0
 public UserInfoDAL()
 {
     db = new EntityFrameworkDbContext();
 }
Ejemplo n.º 28
0
 public ProductViewingInfosRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext)
 {
 }
Ejemplo n.º 29
0
 public HomeController(EntityFrameworkDbContext dbContext)
 {
     _dbContext = dbContext;
 }
Ejemplo n.º 30
0
 public ContentContentTypesRepository(EntityFrameworkDbContext entityFrameworkDbContext) : base(entityFrameworkDbContext)
 {
 }