Exemplo n.º 1
0
 public TEntity Insert(TEntity entity)
 {
     try
     {
         _context.Set <TEntity>().Add(entity);
         int result = _context.SaveChanges();
         return(entity);
     }
     catch (Exception exception)
     {
         throw exception;
     }
 }
        public void GetExamples(CancellationToken cancellationToken)
        {
            var things = db.Things.ToList();
            var po     = new ParallelOptions
            {
                CancellationToken      = cancellationToken,
                MaxDegreeOfParallelism = System.Environment.ProcessorCount
            };

            try
            {
                Parallel.ForEach(things, po, t =>
                {
                    po.CancellationToken.ThrowIfCancellationRequested();
                    log.Information($"Updating {t.Name}");
                    t.Counter++;
                });
            }
            catch (OperationCanceledException ex)
            {
                log.Information("Stopping GetExamples() due to shutdown.");
                return;
            }

            db.SaveChanges();

            log.Information("Finished GetExamples operation.");
        }
Exemplo n.º 3
0
        public static void SeedDatabase(this ExampleDbContext context)
        {
            var todos = new List <TodoItem>
            {
                new TodoItem("Create ASP.NET Core API project", 1),
                new TodoItem("Create simple EF Core database", 1),
                new TodoItem("Add EfCore.GenericServices to web app", 1),
                new TodoItem("Create a example WebAPI controller", 3),
                new TodoItem("Write unit tests", 2),
                new TodoItem("Add Swagger for manual testing", 2)
            };

            context.AddRange(todos);
            var todoHybrids = new List <TodoItemHybrid>
            {
                new TodoItemHybrid("Create ASP.NET Core API project", 1),
                new TodoItemHybrid("Create simple EF Core database", 1),
                new TodoItemHybrid("Add EfCore.GenericServices to web app", 1),
                new TodoItemHybrid("Create a example WebAPI controller", 3),
                new TodoItemHybrid("Write unit tests", 2),
                new TodoItemHybrid("Add Swagger for manual testing", 2)
            };

            context.AddRange(todoHybrids);
            var books = new List <Book>
            {
                new Book("Efcore in action", "test description", DateTime.Now, "test", 50, "")
            };

            context.AddRange(books);

            context.SaveChanges();
        }
        internal static void SeedDatabase(this ExampleDbContext context)
        {
            var todos = new List <TodoItem>
            {
                new TodoItem("Create ASP.NET Core API project", 1),
                new TodoItem("Create simple EF Core database", 1),
                new TodoItem("Add EfCore.GenericServices to web app", 1),
                new TodoItem("Create a example WebAPI controller", 3),
                new TodoItem("Write unit tests", 2),
                new TodoItem("Add Swagger for manual testing", 2)
            };

            context.AddRange(todos);
            var todoHybrids = new List <TodoItemHybrid>
            {
                new TodoItemHybrid("Create ASP.NET Core API project", 1),
                new TodoItemHybrid("Create simple EF Core database", 1),
                new TodoItemHybrid("Add EfCore.GenericServices to web app", 1),
                new TodoItemHybrid("Create a example WebAPI controller", 3),
                new TodoItemHybrid("Write unit tests", 2),
                new TodoItemHybrid("Add Swagger for manual testing", 2)
            };

            context.AddRange(todoHybrids);
            context.SaveChanges();
        }
Exemplo n.º 5
0
 public IActionResult addSample(SampleModel newSample)
 {
     // sanity check
     // if(newSample.sampleBucketID > 0)
     // {
     //     _context.Add(newSample);
     //     _context.SaveChanges();
     //     return Content($"Added Sample {newSample.id} with Bucket {newSample.sampleBucketID}");
     // } else
     // {
     //     return Content($"bucket dropdown error");
     // }
     _context.Add(newSample);
     _context.SaveChanges();
     return(RedirectToAction("listAll"));
 }
Exemplo n.º 6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ExampleDbContext dbContext)
        {
            dbContext.Database.EnsureCreated();
            dbContext.Database.Migrate();

            dbContext.GatewayKeys.AddRange(new[] {
                new Models.GatewayKey("forbidden", "forbidden", GatewayKeyType.Device),
                new Models.GatewayKey("authorized", "authorized", GatewayKeyType.Device, true)
            });

            dbContext.SaveChanges();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
Exemplo n.º 7
0
        public static void SeedTwoTaxRates(this ExampleDbContext context)
        {
            var rateNow   = new TaxRate(DateTime.Today, 4);
            var rate2Days = new TaxRate(DateTime.Today.AddDays(2), 9);

            context.AddRange(rateNow, rate2Days);
            context.SaveChanges();
        }
Exemplo n.º 8
0
 /// <summary>
 /// Seeds the database with Person entities at various stages of data integrity
 /// </summary>
 private void SeedDatabase()
 {
     if (_context.Persons.Count() == 0)
     {
         _context.Add(new Person()
         {
             FirstName = "Maximilian",
             LastName  = "Coutuer",
             Age       = 35,
             Country   = new Country()
             {
                 Name    = "Belgium",
                 Capital = new City()
                 {
                     Name         = "Brussels",
                     Population   = 1199000,
                     HistoricName = "Bruoxala"
                 },
                 Population = 11350000,
             },
         });
         _context.Add(new Person()
         {
             FirstName = "Guðni",
             LastName  = "Jóhannesson",
             Age       = 51,
             Country   = new Country()
             {
                 Name    = "Iceland",
                 Capital = new City()
                 {
                     Name       = "Reykjavik",
                     Population = 112853,
                 },
                 Population = 338349,
             },
         });
         _context.Add(new Person()
         {
             FirstName = "Xi",
             LastName  = "Jinping",
             Country   = null,
         });
         _context.Add(new Person()
         {
             FirstName = "Halimah",
             LastName  = "Yacob",
             Country   = new Country()
             {
                 Name       = "Singapore",
                 Population = 5612000,
                 Capital    = null,
             },
         });
         _context.SaveChanges();
     }
 }
Exemplo n.º 9
0
        public ActionResult OnPostSaveOrder([FromBody] OrderViewModel data)
        {
            var result = "Error! Order is not completed.";

            //save to db
            // populate order

            var order = new Order
            {
                CustomerId  = data.CustomerId,
                OrderDate   = DateTime.UtcNow,
                Items       = new List <OrderItem>(),
                Attachments = new List <OrderAttachment>()
            };

            // populate order details
            foreach (var detail in data.Items)
            {
                var orderItem = new OrderItem
                {
                    ItemNo    = detail.ItemNo,
                    ProductId = detail.ProductId,
                    Quantity  = detail.Quantity
                };
                order.Items.Add(orderItem);
            }
            // populate attachments
            var files     = _uploadFileService.GetFiles(User.Identity.Name, _key);
            var fileNames = data.Attachments.Select(x => x.FileName).ToList();

            foreach (var attachment in data.Attachments)
            {
                order.Attachments.Add(new OrderAttachment {
                    Id       = attachment.Id,
                    FileName = attachment.FileName,
                    Size     = attachment.Size
                });
            }
            _context.Orders.Add(order);
            _context.SaveChanges();
            // remove file stored from uploads folder which not exists in attachments
            foreach (var file in files.Where(x => !fileNames.Contains(x.FileName)))
            {
                var uploads  = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
                var fileName = file.Id + Path.GetExtension(file.FileName);
                if (System.IO.File.Exists(Path.Combine(uploads, fileName)))
                {
                    System.IO.File.Delete(Path.Combine(uploads, fileName));
                }
            }

            result = "Success! Order is completed.";
            //redirect to index page
            return(new JsonResult(result));
        }
        public void TestChangeDifficultyOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

            using (var context = new ExampleDbContext(options))
            {
                context.Database.EnsureCreated();
                context.Add(new TodoItem("Test", 1));
                context.SaveChanges();

                //ATTEMPT
                var item = context.TodoItems.Single();
                item.ChangeDifficulty(2);
                context.SaveChanges();

                //VERIFY
                context.TodoItems.Single().Difficulty.ShouldEqual(2);
            }
        }
        public void TestChangeNameOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

            using (var context = new ExampleDbContext(options))
            {
                context.Database.EnsureCreated();
                context.Add(new TodoItem("Test", 1));
                context.SaveChanges();

                //ATTEMPT
                var item   = context.TodoItems.Single();
                var status = item.ChangeName("New Name");
                context.SaveChanges();

                //VERIFY
                status.IsValid.ShouldBeTrue(status.GetAllErrors());
                context.TodoItems.Single().Name.ShouldEqual("New Name");
            }
        }
        public IActionResult HandCodedUpdate(int id, JsonPatchDocument <TodoItemHybrid> patch, [FromServices] ExampleDbContext context)
        {
            var entity = context.Find <TodoItemHybrid>(id);

            if (entity == null)
            {
                return(NoContent());
            }
            patch.ApplyTo(entity);
            context.SaveChanges();
            return(Ok());
        }
Exemplo n.º 13
0
        public static List <ProductStock> SeedExampleProductStock(this ExampleDbContext context)
        {
            var prodStocks = new List <ProductStock>
            {
                new ProductStock("Product1", 5),
                new ProductStock("Product2", 10),
                new ProductStock("Product3", 20),
            };

            context.AddRange(prodStocks);
            context.SaveChanges();
            return(prodStocks);
        }
        protected virtual Guid SaveIt()
        {
            using (var dbContext = new ExampleDbContext(_dbContextOptions))
            {
                var newThing = new EfcThing
                {
                    Value = 45.0
                };
                dbContext.Add(newThing);
                dbContext.SaveChanges();

                return(newThing.Id);
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile("appsettings.json");

            var configuration = configBuilder.Build();

            using var sqlServerDbContext = new ExampleDbContext(configuration, DatabaseType.SqlServer);
            using var postgresDbContext  = new ExampleDbContext(configuration, DatabaseType.PostgreSql);
            var personToAdd = new Person("Tom", "Brady", new DateTime(1980, 10, 10));

            sqlServerDbContext.Person.Add(personToAdd);
            postgresDbContext.Person.Add(personToAdd);
            sqlServerDbContext.SaveChanges();
            postgresDbContext.SaveChanges();
        }
Exemplo n.º 16
0
        public void TestCheckSaveChangesReturningCount()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

            using (var context = new ExampleDbContext(options))
            {
                context.Database.EnsureCreated();

                //ATTEMPT
                context.Add(new TaxRate(DateTime.UtcNow, 4));
                var numUpdates = context.SaveChanges();

                //VERIFY
                numUpdates.ShouldEqual(1);
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            ExampleDbContext exampleDbContext = new ExampleDbContext();

            var config = new MapperConfiguration(c => c.AddProfile <Model.Entities.HumanResources.Profiles.PersonProfile>());
            var mapper = config.CreateMapper();

            var newPerson = new Person
            {
                DocumentType   = DocumentType.Dni,
                DocumentNumber = "35000000",
                Birthdate      = DateTime.Now.AddYears(-30),
                FirstName      = "TestUser",
                LastName       = "TestUser"
            };

            exampleDbContext.People.Add(newPerson);
            exampleDbContext.SaveChanges(mapper);
        }
Exemplo n.º 18
0
        public DatabaseFixture()
        {
            // establish an in-memory database
            var dbOptions = new DbContextOptionsBuilder <ExampleDbContext>()
                            .UseInMemoryDatabase(databaseName: "exampleapi")
                            .Options;

            mockExampleDbContext  = new ExampleDbContext(dbOptions);
            this.personController = new PersonController(mockExampleDbContext);

            // seed database with randomly generated test persons
            mockExampleDbContext.Database.EnsureCreated();
            for (int i = 0; i < 10; i++)
            {
                testPersons[i] = CreateRandomPerson();
                mockExampleDbContext.Add(testPersons[i]);
            }
            mockExampleDbContext.SaveChanges();
        }
Exemplo n.º 19
0
        public ExampleController(ExampleDbContext context)
        {
            _context = context;
            if (_context.ExampleEntities.Count() == 0)
            {
                _context.ExampleEntities.Add(new ExampleEntity
                {
                    ExampleName        = "Example Name in DB",
                    ExampleDescription = "Some description",
                    ExampleId          = 15
                });

                _context.ExampleEntities.Add(new ExampleEntity
                {
                    ExampleName        = "Example Name in DB nr 2",
                    ExampleDescription = "Some description nr 2",
                    ExampleId          = 10
                });
                _context.SaveChanges();
            }
        }
Exemplo n.º 20
0
        public void TestCreateTodoViaBizLogicOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExampleDbContext>();

            using (var context = new ExampleDbContext(options))
            {
                context.Database.EnsureCreated();
                var service = new CreateTodoBizLogic(context);

                //ATTEMPT
                var dto = new CreateTodoDto
                {
                    Name       = "Test",
                    Difficulty = 3
                };
                var result = service.BizAction(dto);
                context.SaveChanges();

                //VERIFY
                service.HasErrors.ShouldBeFalse(service.GetAllErrors());
                context.TodoItems.Single().Name.ShouldEqual("Test");
            }
        }
 public void UpdatePerson(Person person)
 {
     using (var ctx = new ExampleDbContext())
     {
         ctx.People.Attach(person);
         ctx.Entry(person).State = EntityState.Modified;
         ctx.SaveChanges();
     }
 }
Exemplo n.º 22
0
 /// <summary>
 /// Save
 /// </summary>
 public void Save()
 {
     _dbContext.SaveChanges();
 }
 public void CreatePerson(Person person)
 {
     using (var ctx = new ExampleDbContext())
     {
         ctx.People.Add(person);
         ctx.SaveChanges();
     }
 }
        public void DeletePerson(int personId)
        {
            using (var ctx = new ExampleDbContext())
            {
                var person = ctx.People.SingleOrDefault(p => p.PersonId == personId);
                if (person == null)
                {
                    throw new ObjectNotFoundException("Invalid person id.");
                }

                ctx.People.Remove(person);
                ctx.SaveChanges();
            }
        }