示例#1
0
        protected virtual void PopulateProjects(int count)
        {
            Shuffle(ProjectNames);

            var names = ProjectNames.Take(count).Distinct();

            //var conflicts = _context.Set<Project>().Join(names, p => p.Name, n => n, (p, n) => n).ToArray();

            //names = names.Except(conflicts);

            var proj = new Project[names.Count()];

            int i = 0;

            foreach (var x in names)
            {
                var dates = GetDates();
                proj[i] = new Project
                {
                    Name        = x,
                    Description = Faker.Lorem.Paragraph(),
                    StartDate   = dates.Item1,
                    EndDate     = dates.Item2,
                    Status      = GetStatus(dates)
                };
                i++;
            }

            _context.AddRange(proj);

            this._context.SaveChanges();

            Console.WriteLine("Added {0} randomly generated projects", proj.Length);
        }
示例#2
0
        /// <summary>
        ///Create a context and initialize the database with test Data
        ///This method runs before each test.
        /// </summary>
        private void InitContext()
        {
            var builder = new DbContextOptionsBuilder <ApplicationContext>()
                          .UseInMemoryDatabase <ApplicationContext>("TestDB.mdf");

            appContext = new ApplicationContext(builder.Options);

            var menus = new List <Menu>
            {
                new Menu {
                    ID = 1, Name = "home", Type = "HOME"
                },
                new Menu {
                    ID = 2, Name = "manage", Type = "SIDEBAR"
                },
                new Menu {
                    ID = 3, Name = "settings", Type = "SIDEBAR"
                },
                new Menu {
                    ID = 4, Name = "account", Type = "SIDEBAR"
                },
                new Menu {
                    ID = 5, Name = "profile", Type = "SUBMENU", ParentID = 4
                }
            };
            var categories = new List <Category>
            {
                new Category {
                    ID = 1, Name = "vehicles"
                },
                new Category {
                    ID = 2, Name = "gardening"
                },
                new Category {
                    ID = 3, Name = "travel"
                },
                new Category {
                    ID = 4, Name = "fashion"
                },
                new Category {
                    ID = 5, Name = "cars", ParentID = 2
                }
            };

            var adverts = GetAdvert();

            appContext.AddRange(menus);
            appContext.AddRange(categories);
            appContext.AddRange(adverts);
            int changed = appContext.SaveChanges();
        }
示例#3
0
        /// <summary>
        /// Inserir vários objetos de tipos diferentes no banco de dados
        /// </summary>
        private static void InserirObjetosDeTiposDiferentesEmMassa()
        {
            var db = new ApplicationContext();

            // Objetos diferentes com AddRange
            var produto = new Produto
            {
                Descricao    = "Produto Teste 2",
                CodigoBarras = "1234567891231",
                Valor        = 10m,
                TipoProduto  = TipoDoProduto.MercadoriaParaRevenda,
                Ativo        = true
            };

            var cliente = new Cliente
            {
                Nome     = "Rafael Almeida",
                CEP      = "99999000",
                Cidade   = "Itabaiana",
                Estado   = "SE",
                Telefone = "99000001111"
            };

            db.AddRange(produto, cliente);

            var registros = db.SaveChanges();

            Console.WriteLine($"Foram afetados {registros} registros");
        }
示例#4
0
 public static void Initializer(ApplicationContext context)
 {
     if (context.Candidates.Count() == 0)
     {
         context.AddRange(
             new Candidate
         {
             Name       = "Oleg Bezhok",
             Age        = 19,
             Experience = 1,
             Position   = "Junior",
             Salary     = 500,
             StartDate  = DateTime.Now,
             Resume     = "/Content/Бежок Олег Александрович.doc"
         },
             new Candidate
         {
             Name       = "Sasha Lvova",
             Age        = 18,
             Experience = 1,
             Position   = "Junior",
             Salary     = 300,
             StartDate  = DateTime.Now,
             Resume     = "/Content/Бежок Олег Александрович.doc"
         }
             );
         context.SaveChanges();
     }
 }
示例#5
0
        private static void InserirDadosEmMassa()
        {
            var produto = new Produto
            {
                Descricao    = "Produto Teste",
                CodigoBarras = "1234567891231",
                Valor        = 10m,
                TipoProduto  = TipoProduto.MercadoriaParaRevenda,
                Ativo        = true
            };

            var cliente = new Cliente
            {
                Nome     = "Eu mesmo 2",
                CEP      = "34685974",
                Cidade   = "Betim",
                Estado   = "MG",
                Telefone = "31999999999"
            };

            using var dbContext = new ApplicationContext();
            dbContext.AddRange(produto, cliente);

            var registros = dbContext.SaveChanges();

            Console.WriteLine(registros);
        }
示例#6
0
        private static void InserirDadosEmMassa()
        {
            var produto = new Produto
            {
                Descricao      = "Produto teste",
                CodigoDeBarras = "14526941",
                Valor          = 10m,
                TipoProduto    = TipoProduto.Embalagem,
                Ativo          = true
            };


            var cliente = new Cliente
            {
                Nome     = "Cliente teste",
                CEP      = "08081570",
                Cidade   = "Sao paulo",
                Estado   = "SP",
                Telefone = "2516-5246"
            };

            using var db = new ApplicationContext();
            db.AddRange(produto, cliente);
            var registro = db.SaveChanges();

            Console.WriteLine("Dados: " + registro);
        }
示例#7
0
        private static void InserirDadosEmMassa()
        {
            var produto = new Produto
            {
                Descricao    = "Produto Teste",
                CodigoBarras = "322154545",
                Valor        = 10m,
                TipoProduto  = TipoProduto.MercadoriaParaRevenda,
                Ativo        = true
            };

            var cliente = new Cliente
            {
                Nome     = "Renato Francisco",
                CEP      = "99999000",
                Cidade   = "São Paulo",
                Estado   = "SP",
                Telefone = "11999999999"
            };

            using var db = new ApplicationContext();
            db.AddRange(produto, cliente);

            var registros = db.SaveChanges();

            System.Console.WriteLine($"Total registros: {registros}");
        }
示例#8
0
        /// <summary>
        /// Create a context and initialize the database with test Data
        /// This method runs before each test.
        ///
        /// </summary>
        private void InitContext()
        {
            var builder = new DbContextOptionsBuilder <ApplicationContext>()
                          .UseInMemoryDatabase <ApplicationContext>("TestDB.mdf");

            appContext = new ApplicationContext(builder.Options);

            var categories = new List <Category>
            {
                new Category {
                    ID = 1, Name = "vehicles"
                },
                new Category {
                    ID = 2, Name = "gardening"
                },
                new Category {
                    ID = 3, Name = "travel"
                },
                new Category {
                    ID = 4, Name = "fashion"
                },
                new Category {
                    ID = 5, Name = "cars", ParentID = 1
                },
                new Category {
                    ID = 6, Name = "trucks", ParentID = 1
                }
            };

            appContext.AddRange(categories);
            int changed = appContext.SaveChanges();
            //appContext = context;
        }
示例#9
0
        /// <summary>
        /// Create a context and initialize the database with test Data
        /// This method runs before each test.
        ///
        /// </summary>
        private void InitContext()
        {
            var builder = new DbContextOptionsBuilder <ApplicationContext>()
                          .UseInMemoryDatabase <ApplicationContext>("TestDB.mdf");

            appContext = new ApplicationContext(builder.Options);

            var menus = new List <Menu>
            {
                new Menu {
                    ID = 1, Name = "vehicles", Type = "HOME"
                },
                new Menu {
                    ID = 2, Name = "gardening", Type = "HOME"
                },
                new Menu {
                    ID = 3, Name = "travel", Type = "SIDEBAR"
                },
                new Menu {
                    ID = 4, Name = "fashion", Type = "SUBMENU"
                },
                new Menu {
                    ID = 5, Name = "cars", Type = "SUBMENU", ParentID = 1
                },
                new Menu {
                    ID = 6, Name = "trucks", Type = "SUBMENU", ParentID = 1
                }
            };

            appContext.AddRange(menus);
            int changed = appContext.SaveChanges();
            //appContext = context;
        }
示例#10
0
 public IActionResult PostRange([FromBody] IEnumerable <Student> students)
 {
     //additional checks
     _context.AddRange(students);
     _context.SaveChanges();
     return(Created("URI is going here", students));
 }
示例#11
0
        private static void InserirDadosEmMassa()
        {
            var produto = new Produto
            {
                Descricao = "Produto Z",
                Valor     = 17m,
                Tipo      = TipoProduto.Servico,
                Ativo     = true
            };

            var cliente = new Cliente
            {
                Nome     = "Cliente Teste",
                Telefone = "11111111111",
                Cep      = "22222222",
                Cidade   = "João Pessoa",
                Estado   = "PB",
                Email    = "*****@*****.**"
            };

            using var db = new ApplicationContext();

            db.AddRange(produto, cliente);

            var registros = db.SaveChanges();

            Console.WriteLine($"Total Registros: {registros}");
        }
示例#12
0
        private static void AddTestData(ApplicationContext context)
        {
            var task1 = new Tarea
            {
                Id            = 1,
                Nombre        = "Tarea 1",
                Observaciones = "Sin observaciones",
                Facturable    = true,
                Fecha         = DateTime.UtcNow.AddDays(-3)
            };

            var task2 = new Tarea
            {
                Id            = 2,
                Nombre        = "Tarea 2",
                Observaciones = "Sin observaciones",
                Facturable    = false,
                Fecha         = DateTime.UtcNow
            };

            var task3 = new Tarea
            {
                Id            = 3,
                Nombre        = "Tarea 3",
                Observaciones = "Esto es una prueba de observaciones",
                Facturable    = true,
                Fecha         = DateTime.UtcNow.AddDays(-7)
            };

            context.AddRange(task1, task2, task3);
            context.SaveChanges();
        }
        static void TesteRelacionamentoMuitosParaMuitos()
        {
            using (var db = new ApplicationContext())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var ator1 = new Ator()
                {
                    Nome = "Rafael"
                };
                var ator2 = new Ator()
                {
                    Nome = "Pires"
                };
                var ator3 = new Ator()
                {
                    Nome = "Bruno"
                };

                var filme1 = new Filme()
                {
                    Nome = "A volta dos que não foram"
                };
                var filme2 = new Filme()
                {
                    Nome = "De volta para o futuro"
                };
                var filme3 = new Filme()
                {
                    Nome = "Poeira em alto mar"
                };

                ator1.Filmes.Add(filme1);
                ator1.Filmes.Add(filme2);

                ator2.Filmes.Add(filme1);

                filme3.Atores.Add(ator1);
                filme3.Atores.Add(ator2);
                filme3.Atores.Add(ator3);

                db.AddRange(ator1, ator2, filme3);

                db.SaveChanges();

                foreach (var ator in db.Atores.Include(i => i.Filmes).ToList())
                {
                    Console.WriteLine($"Ator: { ator.Nome }");

                    foreach (var filme in ator.Filmes)
                    {
                        Console.WriteLine($"\t Filme: { filme.Nome }");
                    }
                }
            }
        }
        static public void Initialization(ApplicationContext context)
        {
            foreach (var id in context.Applications.Select(e => e.Id))
            {
                var entity = new Application {
                    Id = id
                };
                context.Applications.Attach(entity);
                context.Applications.Remove(entity);
            }
            context.SaveChanges();

            Category action = new Category()
            {
                Name = "Action"
            };

            context.Add(action);
            Category adventure = new Category()
            {
                Name = "Adventure"
            };

            context.Add(adventure);
            Category rpg = new Category()
            {
                Name = "RPG"
            };

            context.Add(rpg);
            context.SaveChanges();

            context.AddRange(
                new Application()
            {
                Name = "ELEX", Category = rpg
            },
                new Application()
            {
                Name = "Little Nightmares", Category = adventure
            },
                new Application()
            {
                Name = "The Bunker", Category = adventure
            },
                new Application()
            {
                Name = "Fortnight", Category = action
            },
                new Application()
            {
                Name = "Nioh", Category = action
            });
            context.SaveChanges();
        }
示例#15
0
        //for in-memory dababase
        private static ApplicationContext SetUpApplicationContext()
        {
            var builder = new DbContextOptionsBuilder <ApplicationContext>();

            builder.UseInMemoryDatabase("FrontApiDatabase");
            var context = new ApplicationContext(builder.Options);

            context.AddRange();
            context.SaveChanges();
            return(context);
        }
示例#16
0
        //public CheckExpirationJob(IConfiguration configuration)
        //{
        //    _configuration = configuration;
        //}

        public async Task Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap          = context.JobDetail.JobDataMap;
            string     connectionString = dataMap.GetString("connectionString");


            var optionsBuilder = new DbContextOptionsBuilder <ApplicationContext>();

            optionsBuilder.UseSqlServer(connectionString);
            using (var db = new ApplicationContext(optionsBuilder.Options))
            {
                var today           = DateTime.UtcNow.Date;
                var beforeTwoMonths = today.AddMonths(-2);
                // понижаем цену - скоро истекает срок годности
                var olds = db.Stocks.Where(x => x.State == Stocks.Сonditions.Default && x.Expiration <= beforeTwoMonths);
                foreach (var stock in olds)
                {
                    stock.Cost *= 0.9M;
                    stock.State = Stocks.Сonditions.Less2MonthExpiration;
                }
                db.SaveChanges();
                // списываем, срок годности истёк
                var expired = db.Stocks.Where(x => x.State == Stocks.Сonditions.Less2MonthExpiration && x.Expiration.Date <= today);
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        var invoice = new SalesInvoice()
                        {
                            When = DateTime.UtcNow
                        };
                        var salesInfos = new List <SalesInfo>();
                        foreach (var stock in expired)
                        {
                            salesInfos.Add(new SalesInfo
                            {
                                Cost      = 0,
                                Count     = stock.Count,
                                ProductId = stock.ProductId
                            });
                        }

                        invoice.ProductInfos = salesInfos;
                        db.AddRange(invoice);
                        db.Stocks.RemoveRange(expired);
                    }
                    catch (Exception ex)
                    {
                        // transaction RollBack
                    }
                }
            }
        }
示例#17
0
        private static void InserirDadosEmMassa()
        {
            var produto = new Produto
            {
                Descricao    = "Produto Teste 3",
                CodigoBarras = "87264531395611",
                Valor        = 5m,
                TipoProduto  = TipoProduto.Servico,
                Ativo        = true
            };

            var cliente = new Cliente
            {
                Nome     = "Onon da Silva",
                Email    = "*****@*****.**",
                CEP      = "89200000",
                Cidade   = "Joinville",
                Estado   = "SC",
                Telefone = "47991153545"
            };

            var lstClientes = new[]
            {
                new Cliente
                {
                    Nome     = "Beltrano de Souza",
                    Email    = "*****@*****.**",
                    CEP      = "89226330",
                    Cidade   = "Joinville",
                    Estado   = "SC",
                    Telefone = "47988239874"
                },
                new Cliente
                {
                    Nome     = "Ciclano Pereira",
                    Email    = "*****@*****.**",
                    CEP      = "89226001",
                    Cidade   = "Joinville",
                    Estado   = "SC",
                    Telefone = "47991150325"
                }
            };

            using var db = new ApplicationContext();

            db.AddRange(produto, cliente);
            db.Clientes.AddRange(lstClientes);

            var registros = db.SaveChanges();

            Console.WriteLine($"Total de registro(s): {registros}");
        }
示例#18
0
        public bool CreateUserTask(TaskModel taskModel, int[] listsId)
        {
            try
            {
                var temp = _context.ToDoLists.Where(l => listsId.Contains(l.Id));
                if (!ListTypeHelper(listsId, taskModel, temp.ToList()))
                {
                    return(false);
                }
                Task task = new Task();

                task = _mapper.Map <TaskModel, Task>(taskModel, cfg =>
                                                     cfg.AfterMap((src, dest) =>
                {
                    dest.Importance = taskModel.Importance == null ? Importance.normal : taskModel.Importance.Value;
                }));

                _context.Tasks.Add(task);
                _context.SaveChanges();

                if (listsId == null || listsId.Length <= 0)
                {
                    ListTask listTask = new ListTask
                    {
                        ListId = 1,
                        TaskId = task.Id
                    };
                    _context.ListTasks.Add(listTask);
                    _context.SaveChanges();
                }
                else
                {
                    List <ListTask> listTasks = new List <ListTask>();
                    for (int i = 0; i < listsId.Length; i++)
                    {
                        listTasks.Add(new ListTask
                        {
                            ListId = listsId[i],
                            TaskId = task.Id
                        });
                    }
                    _context.AddRange(listTasks);
                    _context.SaveChanges();
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#19
0
 public async void CreateAction([FromBody] string data)
 {
     try
     {
         List <Electic_locomotive> electic_Locomotive = JsonConvert.DeserializeObject <List <Electic_locomotive> >(data);
         _context.AddRange(electic_Locomotive);
         await _context.SaveChangesAsync();
     }
     catch (Exception e)
     {
         Trace.WriteLine(e.ToString());
         Console.WriteLine(e.Message);
     }
 }
        private static void InserirClientesEmMassa()
        {
            //var produto = new Produto
            //{
            //    Descricao = "Produto 2 em massa",
            //    CodigoBarras = "121156445",
            //    Valor = 10m,
            //    TipoProduto = TipoProduto.Embalagem,
            //    Ativo = true
            //};

            //var cliente = new Cliente
            //{
            //    Nome = "Paulo H",
            //    CEP = "0000000",
            //    Cidade = "Sao Paulo",
            //    Estado = "SP",
            //    Telefone = "9201700000"
            //};

            var listaClientes = new[]
            {
                new Cliente
                {
                    Nome     = "Paulo H",
                    CEP      = "0000000",
                    Cidade   = "Sao Paulo",
                    Estado   = "SP",
                    Telefone = "9201700000"
                },
                new Cliente
                {
                    Nome     = "Higor",
                    CEP      = "0000000",
                    Cidade   = "Sao Paulo",
                    Estado   = "SP",
                    Telefone = "9201700000"
                },
            };

            using (var db = new ApplicationContext())
            {
                //db.AddRange(produto, cliente);
                db.AddRange(listaClientes);
                //db.Set<Cliente>().AddRange(listaClientes);

                var registros = db.SaveChanges();
                Console.WriteLine("Foi Adicionado {0} Clientes em massa ", registros);
            }
        }
示例#21
0
        private static ApplicationContext SetUpApplicationContext()
        {
            var random  = new Random();
            var builder = new DbContextOptionsBuilder <ApplicationContext>();

            builder.UseInMemoryDatabase("EventListingDatabase" + random.Next());
            var context = new ApplicationContext(builder.Options);

            context.AddRange(
                new Planet {
                Name = "mars", Population = 15
            }

                );
            context.SaveChanges();
            return(context);
        }
示例#22
0
        private ApplicationContext GetInMemoryDatabase()
        {
            var options = new DbContextOptionsBuilder <ApplicationContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .EnableDetailedErrors()
                          .EnableSensitiveDataLogging()
                          .Options;
            var context = new ApplicationContext(options);

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.AddRange(EmployeesDataMock);
            context.SaveChanges();

            return(context);
        }
        static void ExemploDeTabelaPorHeranca()
        {
            using (var db = new ApplicationContext())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var pessoa = new Pessoa {
                    Nome = "Fulano de Tal"
                };
                var instrutor = new Instrutor {
                    Nome = "Rafael Almeida", Tecnologia = ".NET", Desde = DateTime.Now
                };
                var aluno = new Aluno {
                    Nome = "Maria Thysbe", Idade = 31, DataContrato = DateTime.Now.AddDays(-1)
                };

                db.AddRange(pessoa, instrutor, aluno);
                db.SaveChanges();

                var pessoas     = db.Pessoas.AsNoTracking().ToArray();
                var instrutores = db.Instrutores.AsNoTracking().ToArray();
                // var alunos = db.Alunos.AsNoTracking().ToArray();
                var alunos = db.Pessoas.OfType <Aluno>().AsNoTracking().ToArray(); // Sem o uso de DbSet atraves do OffType

                Console.WriteLine("----- Pessoas -----");
                foreach (var pessoaItem in pessoas)
                {
                    Console.WriteLine($"{pessoaItem.Id} -> {pessoaItem.Nome}");
                }

                Console.WriteLine("----- Instrutores -----");
                foreach (var instrutorItem in instrutores)
                {
                    Console.WriteLine($"Id: {instrutorItem.Id} -> {instrutorItem.Nome}, Tecnologia: {instrutorItem.Tecnologia}, Desde: {instrutorItem.Desde}");
                }

                Console.WriteLine("----- Alunos -----");
                foreach (var alunoItem in alunos)
                {
                    Console.WriteLine($"Id: {alunoItem.Id} -> {alunoItem.Nome}, Idade: {alunoItem.Idade}, Data do Contrato: {alunoItem.DataContrato}");
                }
            }
        }
        private static ApplicationContext SetUpApplicationContext()
        {
            var random  = new Random();
            var builder = new DbContextOptionsBuilder <ApplicationContext>();

            builder.UseInMemoryDatabase("EventListingDatabase" + random.Next());
            var context = new ApplicationContext(builder.Options);

            context.AddRange(
                new Spaceship {
                Max_capacity = 30, Utilization = 20
            },
                new Planet {
                Name = "Moon"
            }
                );
            context.SaveChanges();
            return(context);
        }
示例#25
0
        public static void Start()
        {
            ApplicationContext context = new ApplicationContext();
            List <BookEnt>     list    = new List <BookEnt>
            {
                new BookEnt {
                    Name = "ЖД", Author = "Карл Ма", Count = 150, Category = "Еда", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Авто", Author = "Карл Маркс", Count = 50, Category = "Еда", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Транспорт", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Транспорт", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Еда", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Рецепты", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Транспорт", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Еда", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Транспорт", Description = "Книга про авто", Price = 100
                },
                new BookEnt {
                    Name = "Морской", Author = "Стив Джобс", Count = 280, Category = "Транспорт", Description = "Книга про авто", Price = 100
                }
            };

            context.AddRange(list);
            context.SaveChanges();
        }
示例#26
0
        public IActionResult Edit(PurchaseInvoice model)
        {
            var invoice = _context.PurchaseInvoices.Include(x => x.ProductInfos).First(x => x.Id == model.Id);

            if (model.IsOnStock && model.ShippedId != null)
            {
                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {
                        var config = new MapperConfiguration(cfg => cfg.CreateMap <ProductInfo, Models.Stocks>()
                                                             .ForMember(m => m.Id, m => m.Ignore())
                                                             );
                        // Настройка AutoMapper
                        var mapper = new Mapper(config);
                        // сопоставление
                        var stock = mapper.Map <List <Models.Stocks> >(invoice.ProductInfos);

                        _context.AddRange(stock);
                        _context.SaveChanges();

                        invoice.IsOnStock = true;
                        invoice.ShippedId = model.ShippedId;
                        _context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        // transaction RollBack
                    }
                }
            }
            else if (model.ShippedId != null)
            {
                invoice.ShippedId = model.ShippedId;
                _context.SaveChanges();
            }

            return(RedirectToAction("Index"));
        }
示例#27
0
        private static ApplicationContext SetUpApplicationContext()
        {
            var random  = new Random();
            var builder = new DbContextOptionsBuilder <ApplicationContext>();

            builder.UseInMemoryDatabase("EventListingDatabase" + random.Next());
            var context = new ApplicationContext(builder.Options);

            context.AddRange(
                new Log {
                CreatedAt = DateTime.Now, Data = "1", Endpoint = "/1"
            },
                new Log {
                CreatedAt = DateTime.Now, Data = "2", Endpoint = "/2"
            },
                new Log {
                CreatedAt = DateTime.Now, Data = "3", Endpoint = "/3"
            }
                );
            context.SaveChanges();
            return(context);
        }
示例#28
0
        private static void InsertDataRange()
        {
            Product product = new Product()
            {
                Description = "Test",
                BarCode     = "1234567",
                Value       = 10m,
                ProductType = ProductType.MerchandiseForResale,
                Actived     = true
            };

            Customer customer = new Customer()
            {
                CEP   = "999999",
                City  = "Teste",
                Name  = "Teste",
                UF    = "AA",
                Phone = "1111111"
            };

            using ApplicationContext applicationContext = new ApplicationContext();
            applicationContext.AddRange(product, customer);
            applicationContext.SaveChanges();
        }
示例#29
0
        public void CrawlData(string ticker, Timeframe timeframe)
        {
            IList <Candle> resultCandles   = new List <Candle>();
            IList <Candle> allCandles      = new List <Candle>();
            var            iteration       = 1;
            var            fixedDateTime   = DateTime.UtcNow;
            var            needToTerminate = false;
            var            dateTimeFrom    = fixedDateTime;

            do
            {
                switch (timeframe)
                {
                case Timeframe.OneMinute:
                    dateTimeFrom = fixedDateTime.AddDays(-10 * iteration);
                    break;

                case Timeframe.FiveMinute:
                    dateTimeFrom = fixedDateTime.AddDays(-50 * iteration);
                    break;

                case Timeframe.FiveteenMinute:
                    dateTimeFrom = fixedDateTime.AddDays(-150 * iteration);
                    break;

                case Timeframe.ThirtyMinute:
                    dateTimeFrom = fixedDateTime.AddDays(-300 * iteration);
                    break;

                case Timeframe.OneHour:
                    dateTimeFrom = fixedDateTime.AddDays(-600 * iteration);
                    break;

                case Timeframe.SixHour:
                    dateTimeFrom = fixedDateTime.AddDays(-3600 * iteration);
                    break;

                case Timeframe.TwelveHour:
                    dateTimeFrom = fixedDateTime.AddDays(-7200 * iteration);
                    break;

                case Timeframe.OneDay:
                    dateTimeFrom = fixedDateTime.AddDays(-14400 * iteration);
                    break;

                case Timeframe.SevenDay:
                    dateTimeFrom = fixedDateTime.AddDays(-2000 * iteration);
                    break;

                case Timeframe.OneMonth:
                    dateTimeFrom = fixedDateTime.AddDays(-2000 * iteration);
                    break;
                }

                resultCandles = _binanceMananger.GetData(ticker, timeframe, 1000, dateTimeFrom, fixedDateTime);
                if (allCandles.Any() && resultCandles.Any() && resultCandles.Last().Timestamp == allCandles.Last().Timestamp)
                {
                    needToTerminate = true;
                    break;
                }
                else if (!resultCandles.Any())
                {
                    needToTerminate = true;
                    break;
                }

                foreach (var item in resultCandles)
                {
                    allCandles.Add(item);
                }

                iteration++;
                fixedDateTime = allCandles.First().Timestamp;
            }while (!needToTerminate);

            using (ApplicationContext db = new ApplicationContext())
            {
                db.AddRange(allCandles);
                db.SaveChanges();
            }
        }
        public void FillData()
        {
            /*if (!context.TypeOfDocuments.Any())
             * {
             *  TypeOfDocument pasport = new TypeOfDocument { Name = "Паспорт" };
             *  TypeOfDocument pasport1 = new TypeOfDocument { Name = "ВоенныйБилет" };
             *  TypeOfDocument pasport2 = new TypeOfDocument { Name = "СвидетельствоОрождении" };
             *  context.TypeOfDocuments.AddRange(pasport, pasport1, pasport2);
             *  context.SaveChanges();
             * }
             *
             * if (!context.Countries.Any())
             * {
             *  Country country = new Country { CountryName = "Кыргызстан" };
             *  Country country1 = new Country { CountryName = "Таджикистан" };
             *  Country country2 = new Country { CountryName = "Казахстан" };
             *  context.Countries.AddRange(country, country1, country2);
             *  context.SaveChanges();
             * }
             * if (!context.LegalForms.Any())
             * {
             *  LegalForm legalForm = new LegalForm { LegalFormName = "ОсОО" };
             *  LegalForm legalForm1 = new LegalForm { LegalFormName = "ОАО" };
             *  LegalForm legalForm2 = new LegalForm { LegalFormName = "ЗАО" };
             *  context.LegalForms.AddRange(legalForm, legalForm1, legalForm2);
             *  context.SaveChanges();
             * }
             * if (!context.PropertyTypes.Any())
             * {
             *  PropertyType propertyType = new PropertyType { PropertyTypeName = "Государственная" };
             *  PropertyType propertyType1 = new PropertyType { PropertyTypeName = "Частная" };
             *  PropertyType propertyType2 = new PropertyType { PropertyTypeName = "Смешанная" };
             *  context.PropertyTypes.AddRange(propertyType, propertyType1, propertyType2);
             *  context.SaveChanges();
             * }
             * if (!context.Residencies.Any())
             * {
             *  Residency residency = new Residency { ResidencyName = "Резидент" };
             *  Residency residency1 = new Residency { ResidencyName = "НеРезидент" };
             *
             *  context.Residencies.AddRange(residency, residency1);
             *  context.SaveChanges();
             * }
             * if (!context.TaxInspections.Any())
             * {
             *  TaxInspection taxInspection = new TaxInspection { TaxInspectionName = "Ленинский" };
             *  TaxInspection taxInspection1 = new TaxInspection { TaxInspectionName = "Свердловский" };
             *  TaxInspection taxInspection2 = new TaxInspection { TaxInspectionName = "Октябрьский" };
             *  context.TaxInspections.AddRange(taxInspection, taxInspection1, taxInspection2);
             *  context.SaveChanges();
             * }*/
            if (!context.TransactionTypes.Any())
            {
                List <TransactionType> transactions = new List <TransactionType>();
                transactions.Add(TransactionType.Create(TransactionTypesEnum.Debit));
                transactions.Add(TransactionType.Create(TransactionTypesEnum.Credit));


                context.TransactionTypes.AddRange(transactions);
                context.SaveChanges();
            }
            if (!context.ExchangeRateTypes.Any())
            {
                ExchangeRateType exchangeRateType  = ExchangeRateType.Create(ExchangeRateTypesEnum.NBKR);
                ExchangeRateType exchangeRateType1 = ExchangeRateType.Create(ExchangeRateTypesEnum.Market);

                context.ExchangeRateTypes.AddRange(exchangeRateType, exchangeRateType1);
                context.SaveChanges();
            }
            if (!context.TransferStates.Any())
            {
                context.AddRange(
                    TransferState.Create(TransferStatesEnum.Confirmed),
                    TransferState.Create(TransferStatesEnum.NotConfirmed),
                    TransferState.Create(TransferStatesEnum.Canceled),
                    TransferState.Create(TransferStatesEnum.BalanceNotEnough),
                    TransferState.Create(TransferStatesEnum.AccountIsLocked));

                context.SaveChanges();
            }
            if (!context.TypeOfTransfers.Any())
            {
                context.AddRange(
                    TypeOfTransfer.Create(TypeOfTransfersEnum.InnerTransfer),
                    TypeOfTransfer.Create(TypeOfTransfersEnum.InterBankTransfer),
                    TypeOfTransfer.Create(TypeOfTransfersEnum.Conversion));
                context.SaveChanges();
            }
            if (!context.Currencies.Any())
            {
                context.Currencies.Add
                (
                    new Currency {
                    Code = "123", Name = "SOM", IsNativeCurrency = true
                }
                );
                context.SaveChanges();
            }
            if (!context.OurBank.Any())
            {
                Currency currency    = context.Currencies.FirstOrDefault(n => n.IsNativeCurrency == true);
                Account  bankAccount = new Account {
                    Locked = false, CurrencyId = currency.Id, Number = "1234567890123456"
                };
                context.Accounts.Add(bankAccount);
                context.SaveChanges();
                BankInfo bank = new BankInfo {
                    BankName = "OurBank", Email = "*****@*****.**"
                };
                context.BankInfos.Add(bank);
                OurBank ourBank = new OurBank {
                    BIK = "123", AccountId = bankAccount.Id, BankInfoId = bank.Id
                };
                context.OurBank.Add(ourBank);
                context.SaveChanges();
            }
            if (!context.IntervalTypes.Any())
            {
                List <IntervalType> intervalTypes = new List <IntervalType>();

                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceADay));
                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAWeek));
                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceInTwoWeeks));
                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAMonth));
                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAQuarter));
                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAHalfYear));
                intervalTypes.Add(IntervalType.Create(IntervalTypesEnum.OnceAYear));

                context.IntervalTypes.AddRange(intervalTypes);
                context.SaveChanges();
            }


            if (!context.AddressTypes.Any())
            {
                List <AddressType> addressTypes = new List <AddressType>
                {
                    AddressType.Create(AddressTypesEnum.FactAddress),
                    AddressType.Create(AddressTypesEnum.LegalAddress),
                    AddressType.Create(AddressTypesEnum.BirthAddress)
                };

                context.AddRange(addressTypes);
                context.SaveChanges();
            }
        }