protected virtual async Task AsQueryableTest(
            Func <IIncludableQueryable <Product, ICollection <Part> >, Task <List <Product> > > toList)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                IEntityFrameworkRepository <Product> pr = new EntityFrameworkRepository <Product>(db);
                var q = pr
                        .AsQueryable()
                        .Where(p => p.Id > 1)
                        .Skip(2)
                        .Take(40)
                        .OrderBy(p => p.Name)
                        .Include(p => p.Parts);

                // Act
                var pageItems = await toList(q);

                // Assert
                Assert.NotNull(pageItems);
                Assert.Equal(40, pageItems.Count());
            }
        }
        protected virtual async Task FindSql_With_Parameters_And_Pattern_Test(
            Func <IEntityFrameworkRepository <Product>, string, Dictionary <string, object>, string, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                var cr       = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);

                // Act
                var pr     = new EntityFrameworkRepository <Product>(db);
                var result = await find(pr, "SELECT * FROM Product WHERE Id > :Id AND Description <> :Description",
                                        new Dictionary <string, object>
                {
                    { "Description", "XXX" },
                    { "Id", 50 }
                },
                                        @":(\w+)");

                // Assert
                Assert.NotNull(result);
                Assert.Equal(50, result.Count());
            }
        }
        protected virtual async Task Combine_Page_Sort_Include_AsQueryable_Test(
            Func <IQueryable <Product>, Task <List <Product> > > toList)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                IEntityFrameworkRepository <Product> pr = new EntityFrameworkRepository <Product>(db);
                var q = pr
                        .Page(2, 40)
                        .Include("Parts")
                        .SortBy("Name")
                        .AsQueryable();

                // Act
                var pageItems = await toList(q);

                // Assert
                Assert.NotNull(pageItems);
                Assert.Equal(40, pageItems.Count());
            }
        }
        protected virtual async Task Combine_Page_Sort_Include_FindSql_Test(
            Func <IEntityFrameworkRepository <Product>, string, Dictionary <string, object>, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                IEntityFrameworkRepository <Product> pr = new EntityFrameworkRepository <Product>(db)
                                                          .Page(2, 40)
                                                          .Include("Parts")
                                                          .SortBy("Name");

                // Act
                var pageItems = await find(pr, "SELECT * FROM Product WHERE Id > @Id AND Description <> @Description",
                                           new Dictionary <string, object>
                {
                    { "Description", "XXX" },
                    { "Id", 50 }
                });

                // Assert
                Assert.NotNull(pageItems);
                Assert.Equal(50, pr.TotalItems);
                Assert.Equal(10, pageItems.Count());
            }
        }
        public async Task should_add_new_course()
        {
            var testCourse = new Course
            {
                Id               = 4,
                Name             = "C++",
                TeacherId        = 2,
                CourseId         = 1,
                CourseNavigation = null,
                Teacher          = null,
                PupilInCourse    = null
            };

            _sut.Create(testCourse);
            await _sut.UnitOfWork.SaveEntitiesAsync();

            var addedCourse = _context.Course
                              .FirstOrDefault(_ => _.Id == testCourse.Id);

            addedCourse.ShouldNotBeNull();
            addedCourse.Id.ShouldBe(testCourse.Id);
            addedCourse.Name.ShouldBe(testCourse.Name);
            addedCourse.CourseId.ShouldBe(testCourse.CourseId);
            addedCourse.TeacherId.ShouldBe(testCourse.TeacherId);
        }
        protected virtual async Task PageTest(
            int page,
            int pageSize,
            int totalRows,
            int expectedRows,
            Func <IPageableRepository <Product>, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IPageableRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(totalRows);
                cr.Create(category);
                IPageableRepository <Product> pr = new EntityFrameworkRepository <Product>(db)
                                                   .Page(page, pageSize);

                // Act
                var pageItems = await find(pr);

                // Assert
                Assert.NotNull(pageItems);
                Assert.Equal(expectedRows, pageItems.Count());
                Assert.Equal(totalRows, pr.TotalItems);
                Assert.Equal(pageSize == 0 ? 1 : (totalRows / pageSize) + 1, pr.TotalPages);
                Assert.Equal(page, pr.PageNumber);
                Assert.Equal(page < 2 ? 1 : ((page - 1) * pageSize) + 1, pr.StartIndex);
            }
        }
        public void EFCore_Should_Support_Circular_References()
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                var cr = new EntityFrameworkRepository <Category>(db, null, false);
                var c  = CreateCategory(100);
                cr.Create(c);
                cr.SaveChanges();

                // Detach all to avoid expansions already cached in the context
                cr.DetachAll();

                // Act
                var cdb = cr
                          .Include("Products.Parts.Product")
                          .Find().First();

                Assert.NotNull(cdb);
                var products = cdb.Products;

                // Assert
                Assert.NotNull(products);
                Assert.Equal(100, products.Count);
                var product = products.First();
                for (int i = 0; i < 10; i++)
                {
                    Assert.NotNull(product);
                    Assert.NotNull(product.Parts);
                    var part = product.Parts.First();
                    product = part.Product;
                }
            }
        }
Пример #8
0
        // Create Personal Details
        public static async Task <PersonalDetail> CreatePersonalDetails(PersonalDetailViewModel model)
        {
            try
            {
                using (var db = new WebApiProjectDbContext())
                    using (var repo = new EntityFrameworkRepository <WebApiProjectDbContext>(db))
                    {
                        var entity = new PersonalDetail()
                        {
                            Email       = model.Email,
                            FirstName   = model.FirstName,
                            LastName    = model.LastName,
                            BirthDate   = model.BirthDate,
                            PhoneNumber = model.PhoneNumber,
                            Age         = model.Age,
                        };

                        repo.Create <PersonalDetail>(entity);
                        var result = await db.SaveChangesAsync() == 0 ? null : entity;

                        return(result);
                    }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
                return(null);
            }
        }
        public void AddReturnsAModelWithAnId()
        {
            var efRepo = new EntityFrameworkRepository(DbContext);
            var book = ABook("The book");
            var createdBook = (Book) efRepo.Create(book);
            DbContext.SaveChanges();

            Assert.AreEqual(book.Title, createdBook.Title);
            Assert.AreNotEqual(0, createdBook.Id);
        }
        public void CreateWithNullShouldThrowArgument()
        {
            // Arrange
            var context = new Mock <DbContext>();
            var users   = new List <User>();

            context.Setup(m => m.Set <User>()).Returns(new FakeSet <User>(users));
            var entityFrameworkRepository = new EntityFrameworkRepository <User, int>(context.Object);

            // Act
            entityFrameworkRepository.Create(null);
        }
        protected virtual async Task SortByTest(
            bool descendingOrder,
            bool useExpression,
            Func <ISortableRepository <Product>, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                ISortableRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var c = CreateCategory(100);
                cr.Create(c);
                ISortableRepository <Product> unsortedProductRepository = new EntityFrameworkRepository <Product>(db);
                ISortableRepository <Product> sortedProductRepository   = new EntityFrameworkRepository <Product>(db);
                if (descendingOrder)
                {
                    if (useExpression)
                    {
                        sortedProductRepository.SortByDescending("Name");
                    }
                    else
                    {
                        sortedProductRepository.SortByDescending(p => p.Name);
                    }
                }
                else
                if (useExpression)
                {
                    sortedProductRepository.SortBy("Name");
                }
                else
                {
                    sortedProductRepository.SortBy(p => p.Name);
                }

                // Act
                var sortedProducts = await find(sortedProductRepository);

                var unsortedProducts = await find(unsortedProductRepository);

                // Assert
                var sortedList = descendingOrder
          ? sortedProducts.OrderByDescending(p => p.Name)
          : sortedProducts.OrderBy(p => p.Name);
                Assert.NotNull(sortedProducts);
                Assert.Equal(sortedProducts, sortedList);
                Assert.NotNull(unsortedProducts);
                Assert.NotEqual(unsortedProducts, sortedList);
            }
        }
Пример #12
0
        public void ThrowArgumentNullException_WhenTEntityParameterIsNull()
        {
            // Arrange
            var parserDbContext = new Mock <IParserDbContext>();

            var entities = new Mock <IDbSet <MockDbModel> >();

            parserDbContext.Setup(c => c.Set <MockDbModel>()).Returns(entities.Object);

            var entityFrameworkRepository = new EntityFrameworkRepository <MockDbModel>(parserDbContext.Object);

            MockDbModel entity = null;

            // Act & Assert
            Assert.That(
                () => entityFrameworkRepository.Create(entity),
                Throws.InstanceOf <ArgumentNullException>().With.Message.Contains(nameof(entity)));
        }
Пример #13
0
        public void InvokeIQueryableTEntity_AddMethodOnceWithCorrectParameter()
        {
            // Arrange
            var parserDbContext = new Mock <IParserDbContext>();

            var entities = new Mock <IDbSet <MockDbModel> >();

            parserDbContext.Setup(c => c.Set <MockDbModel>()).Returns(entities.Object);

            var entityFrameworkRepository = new EntityFrameworkRepository <MockDbModel>(parserDbContext.Object);

            var entity = new MockDbModel();

            // Act
            entityFrameworkRepository.Create(entity);

            // Assert
            entities.Verify(e => e.Add(entity), Times.Once);
        }
        protected async Task IncludeTest(
            string includes,
            int productRows,
            int expectedProductRows,
            int expectedPartRows,
            Func <IEntityFrameworkRepository <Category>, int?, Task <Category> > getById)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> categoryRepository = new EntityFrameworkRepository <Category>(db)
                                                                           .Include(includes);
                var category = CreateCategory(productRows);
                categoryRepository.Create(category);
                // Detach all to avoid expansions already cached in the context
                categoryRepository.DetachAll();

                // Act
                category = await getById(categoryRepository, category.Id);

                // Assert
                Assert.NotNull(category);
                if (category.Products == null)
                {
                    Assert.Equal(0, expectedProductRows);
                }
                else
                {
                    Assert.Equal(expectedProductRows, category.Products.Count);
                    var product = category.Products.First();
                    if (product.Parts == null)
                    {
                        Assert.Equal(0, expectedPartRows);
                    }
                    else
                    {
                        Assert.Equal(expectedPartRows, product.Parts.Count);
                    }
                }
            }
        }
        public void CreateShouldAddEntity()
        {
            // Arrange
            var context = new Mock <DbContext>();
            var users   = new List <User>();

            context.Setup(m => m.Set <User>()).Returns(new FakeSet <User>(users));
            var entityFrameworkRepository = new EntityFrameworkRepository <User, int>(context.Object);
            var user = new User
            {
                Id = 3
            };

            // Act
            entityFrameworkRepository.Create(user);

            // Assert
            Assert.AreEqual(1, users.Count);
            Assert.AreEqual(3, users[0].Id);
        }
        protected virtual async Task FindSql_No_Parameters_Test(
            Func <IEntityFrameworkRepository <Product>, string, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                var cr       = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);

                // Act
                var pr     = new EntityFrameworkRepository <Product>(db);
                var result = await find(pr, "SELECT * FROM Product");

                // Assert
                Assert.NotNull(result);
                Assert.Equal(100, result.Count());
            }
        }
Пример #17
0
        public async Task should_add_new_class()
        {
            var testClass = new Class
            {
                Id           = 4,
                Name         = "C4",
                TeacherId    = 1,
                PupilInClass = null,
            };

            _sut.Create(testClass);
            await _sut.UnitOfWork.SaveEntitiesAsync();

            var addedClass = _context.Class
                             .FirstOrDefault(_ => _.Id == testClass.Id);

            addedClass.ShouldNotBeNull();
            addedClass.Id.ShouldBe(testClass.Id);
            addedClass.Name.ShouldBe(testClass.Name);
            addedClass.TeacherId.ShouldBe(testClass.TeacherId);
        }
        public void Join_Should_Work_Without_Expansion()
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                var cr = new EntityFrameworkRepository <Category>(db);
                var c  = CreateCategory(100);
                cr.Create(c);

                // Act
                var pr  = new EntityFrameworkRepository <Part>(db);
                var pdb = pr
                          .Find(p => p.Product.Id == 1).First();

                Assert.NotNull(pdb);

                // Assert
                Assert.NotNull(pdb);
            }
        }
Пример #19
0
        public void ReturnCorrectTEntityInstance()
        {
            // Arrange
            var parserDbContext = new Mock <IParserDbContext>();

            var entities = new Mock <IDbSet <MockDbModel> >();

            parserDbContext.Setup(c => c.Set <MockDbModel>()).Returns(entities.Object);

            var entityFrameworkRepository = new EntityFrameworkRepository <MockDbModel>(parserDbContext.Object);

            var expectedReturnerIQueryableTEntityInstance = entities.Object;

            var entity = new MockDbModel();

            // Act
            var actualReturnerTEntityInstance = entityFrameworkRepository.Create(entity);

            // Assert
            Assert.That(actualReturnerTEntityInstance, Is.SameAs(entity));
        }
        protected virtual async Task FindWhereTest(
            Func <IEntityFrameworkRepository <Product>, Expression <Func <Product, bool> >, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                IEntityFrameworkRepository <Product> pr = new EntityFrameworkRepository <Product>(db)
                                                          .Include("Parts");

                // Act
                var pageItems = await find(pr, p => p.Id > 50);

                // Assert
                Assert.NotNull(pageItems);
                Assert.Equal(50, pageItems.Count());
            }
        }
Пример #21
0
        public async Task should_add_new_school()
        {
            var testSchool = new School
            {
                Id               = 4,
                Name             = "MUNI",
                Country          = "CZE",
                SchoolOwnsSeason = null,
                Teacher          = null
            };

            _sut.Create(testSchool);
            await _sut.UnitOfWork.SaveEntitiesAsync();

            var addedSchool = _context.School
                              .FirstOrDefault(_ => _.Id == testSchool.Id);

            addedSchool.ShouldNotBeNull();
            addedSchool.Id.ShouldBe(testSchool.Id);
            addedSchool.Name.ShouldBe(testSchool.Name);
            addedSchool.Country.ShouldMatch(testSchool.Country);
        }
        protected virtual async Task GetById_Alternative_Key_Test(
            Func <IEntityFrameworkRepository <Order>, object, Task <Order> > getById)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Order> r =
                    new EntityFrameworkRepository <Order>(db, o => o.OrderKey);
                var order = new Order {
                    OrderDate = DateTime.Now
                };
                r.Create(order);

                // Act
                var result = await getById(r, order.OrderKey);

                // Assert
                Assert.True(order.OrderKey > 0);
                Assert.NotNull(result);
            }
        }
Пример #23
0
        public async Task <bool> Add(T entity)
        {
            try
            {
                _errors.Clear();
                _errorDetail.Clear();
                using (var db = new WebApiProjectDbContext())
                    using (var repo = new EntityFrameworkRepository <WebApiProjectDbContext>(db))
                    {
                        repo.Create <T>(entity);
                        return(await db.SaveChangesAsync() == 0 ? false : true);
                    }
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);

                //Add Error message
                _errors.Add("There was an error trying to send the information to the database ");
                return(false);
            }
        }
        public void EFCore_Should_Not_Support_Lazy_Load()
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                var cr = new EntityFrameworkRepository <Category>(db, null, false);
                var c  = CreateCategory(100);
                cr.Create(c);
                cr.SaveChanges();

                // Detach all to avoid expansions already cached in the context
                cr.DetachAll();

                // Act
                var cdb = cr.Find().First();
                Assert.NotNull(cdb);

                // Assert
                // Looks like lazy loading is not supported in EF Core
                Assert.Null(cdb.Products);
            }
        }
        protected virtual async Task FindSql_Wrong_Parameter_Test(
            Func <IEntityFrameworkRepository <Product>, string, Dictionary <string, object>, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                var cr       = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                var pr         = new EntityFrameworkRepository <Product>(db);
                var sql        = "SELECT * FROM Product WHERE Id > @Id";
                var parameters = new Dictionary <string, object> {
                    { "Wrong", 1 }
                };

                // Act
                // Assert
                await Assert.ThrowsAsync <ArgumentException>(async() => await find(pr, sql, null));

                await Assert.ThrowsAsync <ArgumentException>(async() => await find(pr, sql, parameters));
            }
        }
        public async Task should_add_new_teacher()
        {
            var testTeacher = new Teacher
            {
                Id        = 5,
                Firstname = "Geralt",
                Lastname  = "Of Rivia",
                SchoolId  = 3,
                School    = null,
                Class     = null,
                Course    = null
            };

            _sut.Create(testTeacher);
            await _sut.UnitOfWork.SaveEntitiesAsync();

            var addedTeacher = _context.Teacher
                               .FirstOrDefault(_ => _.Id == testTeacher.Id);

            addedTeacher.ShouldNotBeNull();
            addedTeacher.Firstname.ShouldBe(testTeacher.Firstname);
            addedTeacher.Lastname.ShouldBe(testTeacher.Lastname);
            addedTeacher.SchoolId.ShouldBe(testTeacher.SchoolId);
        }
        protected virtual async Task Combine_Page_Sort_Include_Find_Test(
            Func <IPageableRepository <Product>, Task <IEnumerable <Product> > > find)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                IEntityFrameworkRepository <Product> pr = new EntityFrameworkRepository <Product>(db)
                                                          .Page(2, 40)
                                                          .Include("Parts")
                                                          .SortBy("Name");

                // Act
                var pageItems = await find(pr);

                // Assert
                Assert.NotNull(pageItems);
                Assert.Equal(40, pageItems.Count());
                Assert.Equal(100, pr.TotalItems);
            }
        }
        protected virtual async Task GetByIdTest(
            Func <IEntityFrameworkRepository <Product>, object, Task <Product> > getById)
        {
            // Create new empty database
            using (var db = new SQLiteContext())
            {
                // Arrange
                IEntityFrameworkRepository <Category> cr = new EntityFrameworkRepository <Category>(db);
                var category = CreateCategory(100);
                cr.Create(category);
                IEntityFrameworkRepository <Product> pr = new EntityFrameworkRepository <Product>(db)
                                                          .Include(p => p.Category)
                                                          .Include(p => p.Parts);

                // Act
                var product = await getById(pr, 1);

                // Assert
                Assert.NotNull(product);
                Assert.Equal(1, product.Id);
                Assert.NotNull(product.Category);
                Assert.NotNull(product.Parts);
            }
        }
        public void ShouldKnowToTalkToContextAndDbSetOnCreateRHINO()
        {
            var mocks = new Rhino.Mocks.MockRepository();
            var dbContext = mocks.StrictMock<PukuDbContext>();
            var dbSet = mocks.StrictMock<IDbSet<Book>>();
            var newBook = new Book {Title = "Book"};

            With.Mocks(mocks).Expecting(() =>
                {
                    Expect.Call(dbContext.GetDbSet<Book>()).Return(dbSet);
                    Expect.Call(dbSet.Add(newBook));
                })
                .Verify(() =>
                {
                    var efRepo = new EntityFrameworkRepository(dbContext);
                    efRepo.Create(newBook);
                });
        }
Пример #30
0
 // POST api/values
 public void Post([FromBody] Genre band)
 {
     _repository.Create(band, "elcapo");
     _repository.Save();
 }