コード例 #1
0
        public async Task TestSaveChangesAsyncAddNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                nameof(TestSqlSaveChanges));


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    await noSqlContext.Database.EnsureCreatedAsync();

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    await sqlContext.SaveChangesAsync();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.SingleOrDefault(p => p.BookId == book.BookId);
                    noSqlBook.ShouldNotBeNull();
                    noSqlBook.AuthorsOrdered.ShouldEqual("Author1, Author2");
                    noSqlBook.ReviewsCount.ShouldEqual(2);
                }
        }
コード例 #2
0
        public void TestAverageReviewSqlServerOk()
        {
            //SETUP
            var options = this.CreateUniqueClassOptionsWithLogging <SqlDbContext>(
                log => _output.WriteLine(log.Message));

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

                var book = DddEfTestData.CreateDummyBookOneAuthor();
                book.AddReview(5, "test", "test");
                context.Add(book);
                context.SaveChanges();

                //ATTEMPT
                var aveReviews = context.Books
                                 .Select(p => p.Reviews.Select(y => (double?)y.NumStars).Average())
                                 .Single();

                //VERIFY

                aveReviews.ShouldEqual(5);
            }
        }
コード例 #3
0
        public async Task <Response> Insert([FromForm] ServicePrice model)
        {
            Response _objResponse = new Response();

            try
            {
                if (ModelState.IsValid)
                {
                    model.CreatedDate = DateTime.Now;
                    model.UpdatedDate = DateTime.Now;
                    _context.Add(model);
                    await _context.SaveChangesAsync();

                    _objResponse.Status = "Success";
                    _objResponse.Data   = null;
                }
                else
                {
                    _objResponse.Status = "Validation Error";
                    _objResponse.Data   = null;
                }
            }
            catch (Exception ex)
            {
                _objResponse.Data   = null;
                _objResponse.Status = ex.ToString();
                Console.WriteLine("\nMessage ---\n{0}", ex.ToString());
                Console.WriteLine("\nStackTrace ---\n{0}", ex.StackTrace);
            }
            return(_objResponse);
        }
コード例 #4
0
        public async Task TestSaveChangesAsyncUpdatesNoSqlFail()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATABASENAME");


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookOneAuthor();
                    sqlContext.Add(book);
                    var ex = await Assert.ThrowsAsync <HttpException>(async() => await sqlContext.SaveChangesAsync());

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                }
        }
コード例 #5
0
        public async Task TestNoSqlBookUpdaterFail_NoBookAddedToSqlDatabase()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATASBASENAME");


            using (var sqlContext = new SqlDbContext(_sqlOptions))
                using (var noSqlContext = new NoSqlDbContext(builder.Options))
                {
                    await sqlContext.Database.EnsureCreatedAsync();

                    var updater = new NoSqlBookUpdater(noSqlContext);

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookOneAuthor();
                    sqlContext.Add(book);
                    var numBooksChanged = updater.FindNumBooksChanged(sqlContext);
                    var ex = await Assert.ThrowsAsync <CosmosException>(async() =>
                                                                        await updater.CallBaseSaveChangesWithNoSqlWriteInTransactionAsync(sqlContext, numBooksChanged,
                                                                                                                                          () => sqlContext.SaveChangesAsync()));

                    //VERIFY
                    ex.Message.ShouldStartWith("Response status code does not indicate success: 404 Substatus:");
                    numBooksChanged.ShouldEqual(1);
                    sqlContext.Books.Count().ShouldEqual(0);
                }
        }
コード例 #6
0
        public async Task TestNoSqlBookUpdaterOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using var sqlContext   = new SqlDbContext(_sqlOptions);
            using var noSqlContext = new NoSqlDbContext(builder.Options);

            await sqlContext.Database.EnsureCreatedAsync();

            await noSqlContext.Database.EnsureCreatedAsync();

            var updater = new NoSqlBookUpdater(noSqlContext);

            //ATTEMPT
            var book = DddEfTestData.CreateDummyBookOneAuthor();

            sqlContext.Add(book);
            var numBooksChanged = updater.FindNumBooksChanged(sqlContext);
            await updater.CallBaseSaveChangesWithNoSqlWriteInTransactionAsync(sqlContext, numBooksChanged,
                                                                              () => sqlContext.SaveChangesAsync());

            //VERIFY
            numBooksChanged.ShouldEqual(1);
            sqlContext.Books.Count().ShouldEqual(1);
            noSqlContext.Books.Find(book.BookId).ShouldNotBeNull();
        }
コード例 #7
0
        public void AddFac(FactureDTO f, SqlDbContext dbContext)
        {
            Facture fac = new Facture(f);

            dbContext.Add(fac);
            dbContext.SaveChanges();
        }
コード例 #8
0
        public void TestSaveChangesDeleteNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    sqlContext.SaveChanges();

                    //ATTEMPT
                    sqlContext.Remove(book);
                    sqlContext.SaveChanges();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                    var noSqlBook = noSqlContext.Books.SingleOrDefault(p => p.BookId == book.BookId);
                    noSqlBook.ShouldBeNull();
                }
        }
コード例 #9
0
        public void TestSaveChangesUpdatesNoSqlFail()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                "UNKNOWNDATABASENAME");


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();

                    //ATTEMPT
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    var ex = Assert.Throws <CosmosException> (() => sqlContext.SaveChanges());

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(0);
                    ex.Message.ShouldStartWith("Response status code does not indicate success: 404 Substatus:");
                }
        }
コード例 #10
0
        public void TestSaveChangesIndirectUpdatesNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    sqlContext.SaveChanges();
                }
            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    //ATTEMPT
                    var book = sqlContext.Books.Include(x => x.Reviews).Single();
                    book.AddReview(5, "xxx", "yyy");
                    sqlContext.SaveChanges();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.Single(p => p.BookId == book.BookId);
                    noSqlBook.ReviewsCount.ShouldEqual(3);
                }
        }
コード例 #11
0
 // Méthode utilisée une seule fois pour injecter dans la base de donnée les factures
 // créées préalablement en dur dans le code
 public void addAllFac(List <Facture> facList, SqlDbContext dbContext)
 {
     foreach (Facture f in facList)
     {
         dbContext.Add(f);
     }
     dbContext.SaveChanges();
 }
コード例 #12
0
 /// <summary>
 /// 新增
 /// </summary>
 /// <param name="article"></param>
 /// <returns></returns>
 public bool InsertArticle(Article article)
 {
     sqlDbContext.Add(article);
     if (sqlDbContext.SaveChanges() > 0)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
コード例 #13
0
        public async Task <IActionResult> Create(Deposit item1)
        {
            if (ModelState.IsValid)
            {
                item1.Sum = item1.StartSum;
                _context.Add(item1);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index), new { id = item1.UserId }));
            }
            ViewData["CurrencyId"] = new SelectList(_context.Set <Currency>(), "Id", "Id", item1.CurrencyId);
            ViewData["UserId"]     = new SelectList(_context.Employees, "Id", "Id", item1.UserId);
            return(View());
        }
コード例 #14
0
ファイル: Repository.cs プロジェクト: dewitivan777/CRM-API
        public void Add(T entity)
        {
            using (var db = new SqlDbContext(_options))
            {
                var result = db.Set <T>().FirstOrDefault(x => x.Id == entity.Id);
                if (result != null)
                {
                    return;
                }

                db.Add(entity);
                db.SaveChanges();
            }
        }
コード例 #15
0
        public async Task <bool> CreateEmployee(Employee employee)
        {
            employee.Id = Guid.NewGuid().ToString();
            _dbContext.Add(employee);
            try
            {
                await _dbContext.SaveChangesAsync();

                return(true);
            }
            catch (DbUpdateException)
            {
                return(false);
            }
        }
コード例 #16
0
        public IActionResult CreateUser(string Name, int Age)
        {
            if (string.IsNullOrEmpty(Name))
            {
                return(Ok("姓名不为空"));
            }
            Users user = new Users
            {
                Name = Name,
                Age  = Age
            };

            _context.Add(user);
            return(Ok(_context.SaveChanges() == 1 ? "新增成功" : "新增失败"));
        }
コード例 #17
0
        public TestScalarFunctions(ITestOutputHelper output)
        {
            _output = output;

            var options = this.CreateUniqueClassOptions <SqlDbContext>();

            using (var context = new SqlDbContext(options))
            {
                context.Database.EnsureCreated();
                var filepath = TestData.GetFilePath(@"..\..\EfCoreSqlAndCosmos\wwwroot\AddUserDefinedFunctions.sql");
                ApplyScriptsToDatabase.ExecuteScriptFileInTransaction(context, filepath);
                context.WipeAllDataFromDatabase();

                var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                context.Add(book);
                context.SaveChanges();
            }
        }
コード例 #18
0
        public async Task <IdentityResult> CreateAsync(IdentityUser user, string password)
        {
            password = password.Trim();

            if (string.IsNullOrEmpty(password) || password.Length < 7)
            {
                return(new IdentityResult()
                {
                    Errors = new List <string> {
                        "Password must be at least 7 characters"
                    },
                    Succeeded = false
                });
            }

            using (var db = new SqlDbContext(_options))
            {
                try
                {
                    var dbUser = db.IdentityUser.FirstOrDefault(tbl => tbl.Id == user.Id);

                    if (dbUser == null)
                    {
                        user.CreatedOn = DateTime.Now;
                        // Normalize to lower to match the current user search. Or should we keep a copy of the original?
                        user.Email    = user.Email.ToLower();
                        user.UserName = user.UserName.ToLower();

                        user.PasswordHash = _hasher.HashPassword(user.Id, password);

                        db.Add(user);
                    }
                    await db.SaveChangesAsync();
                }
                catch (Exception exc)
                {
                }

                return(new IdentityResult()
                {
                    Succeeded = true
                });
            }
        }
コード例 #19
0
        public void TestAddBookOk()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <SqlDbContext>();

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

                //ATTEMPT
                context.Add(DddEfTestData.CreateDummyBookOneAuthor());
                var changes = BookChangeInfo.FindBookChanges(context.ChangeTracker.Entries().ToList(), context);

                //VERIFY
                changes.Single().BookId.ShouldNotEqual(Guid.Empty);
                changes.Single().State.ShouldEqual(EntityState.Added);
            }
        }
コード例 #20
0
        public async Task <Response> Insert([FromForm] Customer model)
        {
            Response _objResponse = new Response();

            try
            {
                List <Customer> customers = await _context.tblCustomer.Where(u => u.CustomerEmail == model.CustomerEmail).ToListAsync();

                if (customers.Count > 0)
                {
                    _objResponse.Status = "Email Already Exists!";
                    _objResponse.Data   = null;
                }
                else
                {
                    if (ModelState.IsValid)
                    {
                        model.CreatedDate = DateTime.Now;
                        model.UpdatedDate = DateTime.Now;
                        model.CustomerOTP = globalData.GenerateRandomNo().ToString();
                        _context.Add(model);
                        await _context.SaveChangesAsync();

                        _objResponse.Status = "Success";
                        _objResponse.Data   = "";
                        var a = Task.Factory.StartNew(() => globalData.SendEmail("Dear User, <br /> Please Enter the OTP " + model.CustomerOTP + "to verify your account", "Please Verify Email | MunyFinds.com", model.CustomerEmail));
                    }
                    else
                    {
                        _objResponse.Status = "Please enter correct data";
                        _objResponse.Data   = null;
                    }
                }
            }
            catch (Exception ex)
            {
                _objResponse.Data   = null;
                _objResponse.Status = ex.ToString();
                Console.WriteLine("\nMessage ---\n{0}", ex.ToString());
                Console.WriteLine("\nStackTrace ---\n{0}", ex.StackTrace);
            }
            return(_objResponse);
        }
コード例 #21
0
        public virtual async Task <T> AddAsync <T>(T item, CancellationToken token = default) where T : class
        {
            await _semaphore.WaitAsync(token);

            try
            {
                _context.Add(item);
                if (await _context.SaveChangesAsync(token) == 1)
                {
                    return(item);
                }
                ;

                throw new DbAddFailedException();
            }
            finally
            {
                _semaphore.Release();
            }
        }
コード例 #22
0
        public async Task <IActionResult> Create(Credit item1)
        {
            if (ModelState.IsValid)
            {
                if (item1.Type == CreditType.Monthly)
                {
                    var percent = item1.Percent * 0.01 / 12;
                    var koef    = (percent * Math.Pow(1 + percent, item1.ContractTerm * 12)) / (Math.Pow(1 + percent, item1.ContractTerm * 12) - 1);
                    item1.Sum = item1.StartSum * item1.ContractTerm * 12 * (float)koef;
                }
                else
                {
                    item1.Sum = item1.StartSum;
                }

                _context.Add(item1);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index), new { id = item1.UserId }));
            }
            ViewData["CurrencyId"] = new SelectList(_context.Set <Currency>(), "Id", "Id", item1.CurrencyId);
            ViewData["UserId"]     = new SelectList(_context.Employees, "Id", "Id", item1.UserId);
            return(View());
        }
コード例 #23
0
        public async Task TestSaveChangesDirectUpdatesNoSqlOk()
        {
            //SETUP
            var config  = AppSettings.GetConfiguration();
            var builder = new DbContextOptionsBuilder <NoSqlDbContext>()
                          .UseCosmos(
                config["endpoint"],
                config["authKey"],
                GetType().Name);


            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    sqlContext.Database.EnsureCreated();
                    noSqlContext.Database.EnsureCreated();
                    var book = DddEfTestData.CreateDummyBookTwoAuthorsTwoReviews();
                    sqlContext.Add(book);
                    await sqlContext.SaveChangesAsync();
                }
            using (var noSqlContext = new NoSqlDbContext(builder.Options))
                using (var sqlContext = new SqlDbContext(_sqlOptions, new NoSqlBookUpdater(noSqlContext)))
                {
                    //ATTEMPT
                    var book = sqlContext.Books.Single();
                    book.PublishedOn = DddEfTestData.DummyBookStartDate.AddDays(1);
                    await sqlContext.SaveChangesAsync();

                    //VERIFY
                    sqlContext.Books.Count().ShouldEqual(1);
                    var noSqlBook = noSqlContext.Books.Single(p => p.BookId == book.BookId);
                    noSqlBook.PublishedOn.ShouldEqual(DddEfTestData.DummyBookStartDate.AddDays(1));
                    noSqlBook.AuthorsOrdered.ShouldEqual("Author1, Author2");
                    noSqlBook.ReviewsCount.ShouldEqual(2);
                }
        }
コード例 #24
0
 public Restaurant AddRestaurant(Restaurant restaurant)
 {
     _dbContext.Add(restaurant);
     _dbContext.SaveChanges();
     return(restaurant);
 }
コード例 #25
0
 public void Add <TEntity>(TEntity entity) where TEntity : class
 {
     _db.Add <TEntity>(entity);
 }
コード例 #26
0
 public void Add <TEntity>(TEntity item) where TEntity : class
 {
     _db.Add <TEntity>(item);
 }
コード例 #27
0
 public void Add(TEntity item)
 {
     _db.Add(item);
 }
コード例 #28
0
 public void addCa(ChiffreAffaire ca, SqlDbContext dbContext)
 {
     dbContext.Add(ca);
     dbContext.SaveChanges();
 }