public void AlreadyExistingEntityWithIdentityKeyShouldNotBeInserted()
        {
            using (var db = new UnitTestsContext())
            {
                var p = new Person
                {
                    FirstName = "Måns",
                    LastName  = "Tånneryd",
                    BirthDate = new DateTime(1968, 10, 04)
                };

                db.BulkInsertAll(new BulkInsertRequest <Person>
                {
                    Entities = new[] { p }.ToList()
                });


                Assert.AreEqual(1, db.People.Count());

                db.BulkInsertAll(new BulkInsertRequest <Person>
                {
                    Entities = new[] { p }.ToList()
                });

                Assert.AreEqual(1, db.People.Count());
            }
        }
Example #2
0
        public void AlreadyExistingEntityWithUserGeneratedKeyShouldNotBeInserted()
        {
            using (var db = new UnitTestsContext())
            {
                var team1 = new TeamWithUserGeneratedGuidKey()
                {
                    Id   = Guid.NewGuid(),
                    Name = "Team #1",
                };

                db.BulkInsertAll(new BulkInsertRequest <TeamWithUserGeneratedGuidKey>
                {
                    Entities = new[] { team1 }.ToList()
                });


                Assert.AreEqual(1, db.TeamsWithUserGeneratedGuids.Count());

                db.BulkInsertAll(new BulkInsertRequest <TeamWithUserGeneratedGuidKey>
                {
                    Entities = new[] { team1 }.ToList()
                });

                Assert.AreEqual(1, db.TeamsWithUserGeneratedGuids.Count());
            }
        }
Example #3
0
        public void OneToManyWhereTheOneAlreadyExists()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                Parity even = new Parity {
                    Name = "Even", UpdatedAt = now, UpdatedBy = "Måns"
                };
                Parity odd = new Parity {
                    Name = "Odd", UpdatedAt = now, UpdatedBy = "Måns"
                };
                db.BulkInsertAll(new[] { even, odd });

                var numbers = GenerateNumbers(1, 100, even, odd, now).ToArray();
                db.BulkInsertAll(numbers);

                Assert.AreEqual(100, db.Numbers.Count());

                var dbNumbers = db.Numbers.Include(n => n.Parity).ToArray();
                foreach (var number in dbNumbers.Where(n => n.Value % 2 == 0))
                {
                    Assert.AreEqual("Even", number.Parity.Name);
                    Assert.AreEqual(now.ToString("yyyyMMddHHmmss"), number.UpdatedAt.ToString("yyyyMMddHHmmss"));
                }

                foreach (var number in dbNumbers.Where(n => n.Value % 2 != 0))
                {
                    Assert.AreEqual("Odd", number.Parity.Name);
                    Assert.AreEqual(now.ToString("yyyyMMddHHmmss"), number.UpdatedAt.ToString("yyyyMMddHHmmss"));
                }
            }
        }
        public void AddingMotherWithChild()
        {
            var child = new Person
            {
                FirstName = "Arvid",
                LastName  = "Andersson",
                BirthDate = new DateTime(2018, 1, 1),
            };
            var mother = new Person
            {
                FirstName = "Anna",
                LastName  = "Andersson",
                BirthDate = new DateTime(1980, 1, 1),
            };

            mother.Children.Add(child);

            using (var db = new UnitTestsContext())
            {
                var request = new BulkInsertRequest <Person>
                {
                    Entities = new List <Person> {
                        mother
                    },
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes,
                };
                db.BulkInsertAll(request);

                var people = db.People.ToArray();
                Assert.AreEqual(2, people.Length);
            }
        }
        public void AddingEmployeeWithCompany()

        {
            var employee = new Employee
            {
                Name = "John",
            };
            var employer = new Company
            {
                Name = "World Inc",
            };

            employer.ParentCompany = employer;
            employee.Employer      = employer;

            using (var db = new UnitTestsContext())
            {
                var request = new BulkInsertRequest <Employee>
                {
                    Entities = new List <Employee> {
                        employee
                    },
                    EnableRecursiveInsert      = EnableRecursiveInsert.Yes,
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.Yes
                };
                db.BulkInsertAll(request);

                var actual = db.Companies.Include(e => e.Employees).Single();
                Assert.AreEqual("World Inc", actual.Name);
                Assert.AreSame(actual, actual.ParentCompany);
                Assert.AreEqual("John", actual.Employees.Single().Name);
            }
        }
Example #6
0
        public void ExistingEntitiesShouldBeSelectedUsingRuntimeTypes()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                // Save 200 numbers (1 to 200) to the database.
                var numbers = GenerateNumbers(1, 200, now).ToArray();
                db.BulkInsertAll(new BulkInsertRequest <Number>
                {
                    Entities = numbers,
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes
                });

                // Create a list of 100 numbers with values 151 to 250
                numbers = GenerateNumbers(151, 100, now).ToArray();

                // Numbers 151 to 200 out of 151 to 250 should be selected.
                var request = typeof(BulkSelectRequest <>).MakeGenericType(typeof(Number));
                var r       = Activator.CreateInstance(request, new[] { "Value" }, numbers.ToList(), null);

                Type       ex              = typeof(DbContextExtensions);
                MethodInfo mi              = ex.GetMethod("BulkSelectExisting");
                MethodInfo miGeneric       = mi.MakeGenericMethod(new[] { typeof(Number), typeof(Number) });
                object[]   args            = { db, r };
                var        existingNumbers = (List <Number>)miGeneric.Invoke(null, args);

                Assert.AreEqual(50, existingNumbers.Count);
                for (int i = 0; i < 50; i++)
                {
                    Assert.AreSame(numbers[i], existingNumbers[i]);
                }
            }
        }
 public void JoinTablesWithGuidKeysShouldBeProperlyInserted()
 {
     using (var db = new UnitTestsContext())
     {
         var blog = new Blog {
             Name = "My Blog"
         };
         var firstPost = new Post
         {
             Blog = blog,
             Text = "My first blogpost.",
         };
         var visitor = new Visitor
         {
             Name = "Visitor1"
         };
         firstPost.Visitors.Add(visitor);
         var req = new BulkInsertRequest <Post>
         {
             Entities = new[] { firstPost }.ToList(),
             AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
             SortUsingClusteredIndex    = true,
             EnableRecursiveInsert      = EnableRecursiveInsert.Yes
         };
         var response = db.BulkInsertAll(req);
         var posts    = db.Posts
                        .Include(p => p.Blog)
                        .ToArray();
         Assert.AreEqual(1, posts.Count());
     }
 }
        public void CoursesWithSingleInstructorShouldBeBulkInserted()
        {
            using (var db = new UnitTestsContext())
            {
                var instructors = GetInstructors().ToArray();
                var courses     = GetCourses().ToArray();
                courses[0].Instructors.Add(instructors[0]);
                courses[1].Instructors.Add(instructors[0]);
                courses[2].Instructors.Add(instructors[0]);
                courses[3].Instructors.Add(instructors[1]);
                courses[4].Instructors.Add(instructors[1]);
                var request = new BulkInsertRequest <Course>
                {
                    Entities = courses.ToList(),
                    EnableRecursiveInsert      = EnableRecursiveInsert.Yes,
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No
                };
                db.BulkInsertAll(request);

                var dbInstructors = db.Instructors
                                    .Include(i => i.Courses)
                                    .ToArray();
                var dbCourses = db.Courses.ToArray();
                Assert.AreEqual(2, dbInstructors.Length);
                Assert.AreEqual(5, dbInstructors.SelectMany(i => i.Courses).Count());
                Assert.AreEqual(3, dbInstructors[0].Courses.Count);
                Assert.AreEqual(2, dbInstructors[1].Courses.Count);
                Assert.AreSame(dbCourses[0].Instructors.Single(), dbCourses[1].Instructors.Single());
                Assert.AreSame(dbCourses[0].Instructors.Single(), dbCourses[2].Instructors.Single());
                Assert.AreSame(dbCourses[3].Instructors.Single(), dbCourses[4].Instructors.Single());
            }
        }
Example #9
0
        public void OneToManyWhereAllIsNew()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                var numbers = GenerateNumbers(1, 100, now).ToArray();
                var request = new BulkInsertRequest <Number>
                {
                    Entities = numbers,
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes,
                };
                db.BulkInsertAll(request);

                Assert.AreEqual(100, db.Numbers.Count());

                var dbNumbers = db.Numbers.Include(n => n.Parity).ToArray();
                foreach (var number in dbNumbers.Where(n => n.Value % 2 == 0))
                {
                    Assert.AreEqual("Even", number.Parity.Name);
                    Assert.AreEqual(now.ToString("yyyyMMddHHmmss"), number.UpdatedAt.ToString("yyyyMMddHHmmss"));
                }

                foreach (var number in dbNumbers.Where(n => n.Value % 2 != 0))
                {
                    Assert.AreEqual("Odd", number.Parity.Name);
                    Assert.AreEqual(now.ToString("yyyyMMddHHmmss"), number.UpdatedAt.ToString("yyyyMMddHHmmss"));
                }
            }
        }
        public void EntityHierarchyShouldBeInserted()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                var numbers = GenerateNumbers(1, 10, now).ToArray();  // 1-10
                var primes  = GeneratePrimeNumbers(10, numbers, now); // 1,2,3,5,7

                var request = new BulkInsertRequest <Prime>
                {
                    Entities = primes,
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes,
                };
                db.BulkInsertAll(request);

                var actualNumbers = db.Numbers.ToArray();
                var actualPrimes  = db.Primes.ToArray();

                Assert.AreEqual(5, actualNumbers.Length);
                Assert.AreEqual(5, actualPrimes.Length);
                Assert.AreEqual(1, actualPrimes[0].Number.Value);
                Assert.AreEqual(2, actualPrimes[1].Number.Value);
                Assert.AreEqual(3, actualPrimes[2].Number.Value);
                Assert.AreEqual(5, actualPrimes[3].Number.Value);
                Assert.AreEqual(7, actualPrimes[4].Number.Value);
            }
        }
        public void ComplexTypesShouldBeInserted()
        {
            using (var db = new UnitTestsContext())
            {
                // The level entities are used to test EF complex types.
                var expectedLevels = new[]
                {
                    new Level1
                    {
                        Level2 = new Level2
                        {
                            Level2Name = "L2",
                            Updated    = new DateTime(2018, 1, 1)
                        }
                    }
                };
                db.BulkInsertAll(expectedLevels);

                var actualLevels = db.Levels.ToArray();
                Assert.AreEqual(expectedLevels.Length, actualLevels.Length);
                Assert.AreEqual(expectedLevels[0].Id, actualLevels[0].Id);
                Assert.AreEqual(expectedLevels[0].Level2.Level2Name, actualLevels[0].Level2.Level2Name);
                Assert.AreEqual(expectedLevels[0].Level2.Updated.Ticks, actualLevels[0].Level2.Updated.Ticks);
            }
        }
        public void StackOverflowTest()
        {
            using (var db = new UnitTestsContext())
            {
                var i1 = new Instructor
                {
                    FirstName        = "Mickey",
                    LastName         = "Mouse",
                    HireDate         = new DateTime(1928, 5, 15),
                    OfficeAssignment = new OfficeAssignment {
                        Location = "Room 1A"
                    }
                };
                db.Instructors.Add(i1);
                db.SaveChanges();

                var d1 = new Department
                {
                    Name   = "Computer Science",
                    Budget = 10000000,
                };

                var c1 = new Course
                {
                    Credits    = 4,
                    Title      = "Foundations of Data Science",
                    Department = d1
                };

                db.Courses.Add(c1);
                db.SaveChanges();

                i1.Courses.Add(c1);
                db.SaveChanges();

                Assert.AreEqual(1, db.Instructors.SelectMany(i => i.Courses).Distinct().Count());

                var instructor = db.Instructors
                                 .Include(i => i.Courses.Select(c => c.Department))
                                 .Include(i => i.OfficeAssignment)
                                 .Single();

                instructor.InstructorID = 0;
                instructor.OfficeAssignment.InstructorID = 0;

                var request = new BulkInsertRequest <Instructor>
                {
                    Entities = new[] { instructor }.ToList(),
                    EnableRecursiveInsert      = EnableRecursiveInsert.Yes,
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No
                };
                db.BulkInsertAll(request);


                Assert.AreEqual(2, db.Instructors.SelectMany(i => i.Courses).Count());
            }
        }
        public void AddingEmployeeToSubsidiary()
        {
            var corporateGroup = new Company
            {
                Name = "Global Corporation Inc",
            };

            corporateGroup.ParentCompany = corporateGroup;
            var employer = new Company
            {
                Name = "Subsidiary Corporation Inc",
            };

            employer.ParentCompany = corporateGroup;

            var john = new Employee
            {
                Name     = "John",
                Employer = employer
            };
            var adam = new Employee
            {
                Name     = "Adam",
                Employer = employer
            };

            using (var db = new UnitTestsContext())
            {
                var request = new BulkInsertRequest <Employee>
                {
                    Entities = new List <Employee> {
                        john, adam
                    },
                    EnableRecursiveInsert      = EnableRecursiveInsert.Yes,
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.Yes
                };
                db.BulkInsertAll(request);

                var actual = db.Employees
                             .Include(e => e.Employer.ParentCompany)
                             .OrderBy(e => e.Name).ToArray();
                Assert.AreEqual("Adam", actual[0].Name);
                Assert.AreEqual("Subsidiary Corporation Inc", actual[0].Employer.Name);
                Assert.AreSame(actual[0].Employer, actual[1].Employer);

                Assert.AreEqual("John", actual[1].Name);
                Assert.AreEqual("Subsidiary Corporation Inc", actual[1].Employer.Name);

                Assert.AreEqual("Global Corporation Inc", actual[0].Employer.ParentCompany.Name);
                Assert.AreEqual("Global Corporation Inc", actual[1].Employer.ParentCompany.Name);
                Assert.AreSame(actual[0].Employer.ParentCompany, actual[1].Employer.ParentCompany);
            }
        }
Example #14
0
        public void ModifiedEntityShouldBeUpdated()
        {
            using (var db = new UnitTestsContext())
            {
                var blog = new Blog {
                    Name = "My Blog"
                };
                var firstPost = new Post
                {
                    Text         = "My first blogpost.",
                    PostKeywords = new List <Keyword>()
                    {
                        new Keyword {
                            Text = "first"
                        }
                    }
                };
                var secondPost = new Post
                {
                    Text         = "My second blogpost.",
                    PostKeywords = new List <Keyword>()
                    {
                        new Keyword {
                            Text = "second"
                        }
                    }
                };
                blog.BlogPosts.Add(firstPost);
                blog.BlogPosts.Add(secondPost);
                var req = new BulkInsertRequest <Blog>
                {
                    Entities = new[] { blog }.ToList(),
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
                    SortUsingClusteredIndex    = true,
                    EnableRecursiveInsert      = EnableRecursiveInsert.Yes
                };
                var response = db.BulkInsertAll(req);

                var b = db.Blogs.Single();
                Assert.AreEqual("My Blog", b.Name);

                b.Name = "My (modified) Blog";
                db.BulkUpdateAll(new BulkUpdateRequest
                {
                    Entities         = new [] { b },
                    KeyPropertyNames = new [] { "Id" }
                });

                b = db.Blogs.Single();
                Assert.AreEqual("My (modified) Blog", b.Name);
            }
        }
        public void RowWithReservedSqlKeywordAsColumnNameShouldBeInserted()
        {
            using (var db = new UnitTestsContext())
            {
                var e = new ReservedSqlKeyword
                {
                    Identity = 10
                };
                db.BulkInsertAll(new[] { e });

                Assert.AreEqual(10, e.Identity);
            }
        }
        public void InsertEntityWithComputedColumnInTableWithIdentityPrimaryKeyShouldWork()
        {
            using (var db = new UnitTestsContext())
            {
                var instructor = new Instructor
                {
                    FirstName = "Måns",
                    LastName  = "Tånneryd",
                    HireDate  = DateTime.Now.Date,
                };

                db.BulkInsertAll(new[] { instructor });
            }
        }
        public void InsertEntityWithComputedColumnInTableWithUserGeneratedPrimaryKeyShouldWork()
        {
            using (var db = new UnitTestsContext())
            {
                for (int i = 0; i < 10; i++)
                {
                    db.Journals.Add(new Journal()
                    {
                        Id = Guid.NewGuid()
                    });
                }
                db.SaveChanges();

                var batchInvoice = new BatchInvoice {
                    Id = Guid.NewGuid()
                };

                foreach (var journal in db.Journals.ToList())
                {
                    var invoice = new Invoice()
                    {
                        Id = Guid.NewGuid(), Gross = 10, Net = 3
                    };
                    invoice.Journals.Add(new InvoiceItem()
                    {
                        JournalId = journal.Id
                    });
                    batchInvoice.Invoices.Add(new BatchInvoiceItem()
                    {
                        Id = Guid.NewGuid(), Invoice = invoice
                    });
                }

                var req = new BulkInsertRequest <BatchInvoice>
                {
                    Entities = new[] { batchInvoice }.ToList(),
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
                    SortUsingClusteredIndex    = true,
                    EnableRecursiveInsert      = EnableRecursiveInsert.Yes
                };
                var response = db.BulkInsertAll(req);

                Assert.AreEqual(1, db.BatchInvoices.ToArray().Count());
                Assert.AreEqual(10, db.BatchInvoiceItems.ToArray().Count());
                Assert.AreEqual(10, db.Invoices.ToArray().Count());
                Assert.AreEqual(10, db.InvoiceItems.ToArray().Count());
            }
        }
        public void ExistingEntitiesShouldBeSelectedOnSingleKey()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                // Save 200 numbers (1 to 200) to the database.
                var numbers = GenerateNumbers(1, 200, now).ToArray();
                db.BulkInsertAll(new BulkInsertRequest <Number>
                {
                    Entities = numbers,
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes
                });

                // Create a list of 100 numbers with values 151 to 250
                var nums = GenerateNumbers(151, 100, now)
                           .Select(n => new Num {
                    Val = n.Value
                })
                           .ToList();

                // Numbers 151 to 200 from the database should be selected.
                var existingNumbers = db.BulkSelect <Num, Number>(new BulkSelectRequest <Num>
                {
                    Items = nums.ToArray(),
                    KeyPropertyMappings = new[]
                    {
                        new KeyPropertyMapping
                        {
                            ItemPropertyName   = "Val",
                            EntityPropertyName = "Value"
                        },
                    }
                }).ToArray();

                Assert.AreEqual(existingNumbers.Length, 50);
                var expectedNumbers = numbers.Skip(150).Take(50).ToArray();

                for (int i = 0; i < 50; i++)
                {
                    Assert.AreEqual(expectedNumbers[i].Id, existingNumbers[i].Id);
                    Assert.AreEqual(expectedNumbers[i].ParityId, existingNumbers[i].ParityId);
                    Assert.AreEqual(expectedNumbers[i].UpdatedAt.ToString(CultureInfo.InvariantCulture), existingNumbers[i].UpdatedAt.ToString(CultureInfo.InvariantCulture));
                    Assert.AreEqual(expectedNumbers[i].UpdatedBy, existingNumbers[i].UpdatedBy);
                    Assert.AreEqual(expectedNumbers[i].Value, existingNumbers[i].Value);
                }
            }
        }
Example #19
0
 public void OneToManyWithGuidPrimaryKeyInsertingTheTopEntity()
 {
     using (var db = new UnitTestsContext())
     {
         var blog = new Blog {
             Name = "My Blog"
         };
         var firstPost = new Post
         {
             Text         = "My first blogpost.",
             PostKeywords = new List <Keyword>()
             {
                 new Keyword {
                     Text = "first"
                 }
             }
         };
         var secondPost = new Post
         {
             Text         = "My second blogpost.",
             PostKeywords = new List <Keyword>()
             {
                 new Keyword {
                     Text = "second"
                 }
             }
         };
         blog.BlogPosts.Add(firstPost);
         blog.BlogPosts.Add(secondPost);
         var req = new BulkInsertRequest <Blog>
         {
             Entities = new[] { blog }.ToList(),
             AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
             SortUsingClusteredIndex    = true,
             EnableRecursiveInsert      = EnableRecursiveInsert.Yes
         };
         var response = db.BulkInsertAll(req);
         var posts    = db.Posts
                        .Include(p => p.Blog)
                        .ToArray();
         Assert.AreEqual(2, posts.Count());
         Assert.AreEqual(posts[1].Blog, posts[0].Blog);
     }
 }
Example #20
0
        public void OrderOfNExpected()
        {
            using (var db = new UnitTestsContext())
            {
                var coaches = new List <CoachWithUserGeneratedGuidKey>();
                for (int i = 0; i < 1000; i++)
                {
                    var c = new CoachWithUserGeneratedGuidKey
                    {
                        Id        = Guid.NewGuid(),
                        Firstname = $"Coach {i}",
                        Lastname  = $"Lastname",
                    };
                    for (int j = 0; j < 25; j++)
                    {
                        var t = new TeamWithUserGeneratedGuidKey()
                        {
                            Id   = Guid.NewGuid(),
                            Name = $"Team {j}"
                        };
                        c.Teams.Add(t);
                    }

                    coaches.Add(c);
                }


                db.BulkInsertAll(new BulkInsertRequest <CoachWithUserGeneratedGuidKey>
                {
                    Entities = coaches,
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes
                });

                var actual = db.CoachesWithUserGeneratedGuids
                             .Include(c => c.Teams)
                             .ToArray();

                Assert.AreEqual(1000, actual.Count());
                foreach (var coach in actual.ToArray())
                {
                    Assert.AreEqual(25, coach.Teams.Count);
                }
            }
        }
Example #21
0
        public void SelectExistingFromTableWithUserGeneratedGuidAsPrimaryKey()
        {
            using (var db = new UnitTestsContext())
            {
                var teams = new List <TeamWithUserGeneratedGuidKey>();

                // Add ten teams to the database (Team 0 - Team 9)
                for (int i = 0; i < 10; i++)
                {
                    teams.Add(new TeamWithUserGeneratedGuidKey()
                    {
                        Id = Guid.NewGuid(), Name = $"Team #{i}"
                    });
                }

                // Save the ten first teams to the database.
                db.BulkInsertAll(new BulkInsertRequest <TeamWithUserGeneratedGuidKey>
                {
                    Entities = teams,
                });

                // Add another ten teams (Team 10 - Team 19) to
                // the list but not to the database.
                for (int i = 10; i < 20; i++)
                {
                    teams.Add(new TeamWithUserGeneratedGuidKey()
                    {
                        Id = Guid.NewGuid(), Name = $"Team #{i}"
                    });
                }

                // The only teams we should get back out of the 20 teams (Team 0 - Team 19)
                // are the first ten that we saved to the database.
                var existingTeams = db.BulkSelectExisting <TeamWithUserGeneratedGuidKey, TeamWithUserGeneratedGuidKey>(new BulkSelectRequest <TeamWithUserGeneratedGuidKey>(new[] { "Id" }, teams));
                existingTeams = existingTeams.OrderBy(t => t.Name).ToList();
                Assert.AreEqual(10, existingTeams.Count);
                for (int i = 0; i < 10; i++)
                {
                    Assert.AreEqual(teams[i].Id, existingTeams[i].Id);
                    Assert.AreEqual(teams[i].Name, existingTeams[i].Name);
                }
            }
        }
Example #22
0
        public void EntitiesOfDifferentTypeMatchingExistingEntitiesShouldBeSelected()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                // Save 200 numbers (1 to 200) to the database.
                var numbers = GenerateNumbers(1, 200, now).ToArray();
                db.BulkInsertAll(new BulkInsertRequest <Number>
                {
                    Entities = numbers,
                    EnableRecursiveInsert = EnableRecursiveInsert.Yes
                });

                // Create a list of 100 numbers with values 151 to 250
                var nums = GenerateNumbers(151, 100, now)
                           .Select(n => new Num {
                    Val = n.Value
                })
                           .ToList();

                // Numbers 151 to 200 out of 151 to 250 should be selected.
                var existingNumbers = db.BulkSelectExisting <Num, Number>(new BulkSelectRequest <Num>
                {
                    Items = nums,
                    KeyPropertyMappings = new[]
                    {
                        new KeyPropertyMapping
                        {
                            ItemPropertyName   = "Val",
                            EntityPropertyName = "Value"
                        },
                    }
                }).ToArray();

                Assert.AreEqual(50, existingNumbers.Length);
                for (int i = 0; i < 50; i++)
                {
                    Assert.AreEqual(nums[i], existingNumbers[i]);
                }
            }
        }
 public void AddingEmployeeToCompanyWithoutParentCompanySet()
 {
     try
     {
         var employer = new Company
         {
             Name = "World Inc",
         };
         var john = new Employee
         {
             Name     = "John",
             Employer = employer
         };
         var adam = new Employee
         {
             Name     = "Adam",
             Employer = employer
         };
         using (var db = new UnitTestsContext())
         {
             var request = new BulkInsertRequest <Employee>
             {
                 Entities = new List <Employee> {
                     john, adam
                 },
                 EnableRecursiveInsert      = EnableRecursiveInsert.Yes,
                 AllowNotNullSelfReferences = AllowNotNullSelfReferences.Yes
             };
             db.BulkInsertAll(request);
         }
     }
     catch (System.Data.SqlClient.SqlException e)
     {
         Console.WriteLine(e.Message);
         var expectedMessage =
             @"The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint ""FK_dbo_Company_dbo_Company_ParentCompanyId"". The conflict occurred in database ""Tanneryd.BulkOperations.EF6.NET47.ModelFirst.Tests.Models.EF.UnitTestContext"", table ""dbo.Company"", column 'Id'.";
         Assert.AreEqual(expectedMessage, e.Message);
         throw;
     }
 }
        public void BulkInsertIntoTableWithoutNavPropertiesShouldWork()
        {
            using (var db = new UnitTestsContext())
            {
                var entities = new List <Price>
                {
                    new Price()
                    {
                        Date = new DateTime(2019, 1, 1), Name = "ERICB", Value = 80
                    },
                    new Price()
                    {
                        Date = new DateTime(2019, 1, 2), Name = "ERICB", Value = 81
                    },
                    new Price()
                    {
                        Date = new DateTime(2019, 1, 3), Name = "ERICB", Value = 82
                    },
                    new Price()
                    {
                        Date = new DateTime(2019, 1, 4), Name = "ERICB", Value = 0
                    },
                    new Price()
                    {
                        Date = new DateTime(2019, 1, 5), Name = "ERICB", Value = 86
                    }
                };


                var request = new BulkInsertRequest <Price>
                {
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
                    EnableRecursiveInsert      = EnableRecursiveInsert.NoButRetrieveGeneratedPrimaryKeys,
                    Entities = entities.ToArray()
                };

                db.BulkInsertAll(request);
            }
        }
        public void RowWithCompositePrimaryKeyShouldBeInserted()
        {
            using (var db = new UnitTestsContext())
            {
                var x = new Coordinate
                {
                    Value = 1
                };
                var y = new Coordinate
                {
                    Value = 2
                };
                var p = new Point
                {
                    XCoordinate = x,
                    YCoordinate = y,
                    Value       = 100
                };
                db.BulkInsertAll(new[] { p }, null, true);

                Assert.AreEqual(100, p.Value);
            }
        }
        public void FillingUpTableWithPrimaryKeyColumnOnlyShouldBePossible()
        {
            using (var db = new UnitTestsContext())
            {
                var entities = new List <EmptyTable>();
                for (int i = 0; i < 1000; i++)
                {
                    entities.Add(new EmptyTable());
                }

                var request = new BulkInsertRequest <EmptyTable>
                {
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
                    EnableRecursiveInsert      = EnableRecursiveInsert.NoButRetrieveGeneratedPrimaryKeys,
                    Entities = entities
                };

                db.BulkInsertAll(request);
                //for (int i = 0; i < 1000; i++)
                //{
                //    Console.WriteLine(entities[i].Id);
                //}
            }
        }
        public void PrimaryKeyColumnMappedToPropertyWithDifferentNameShouldBeAllowed()
        {
            using (var db = new UnitTestsContext())
            {
                var now = DateTime.Now;

                // The Parity table is defined with a pk column named Key but
                // it is mapped to the property Id. There was a user reporting that
                // this did not work properly so we want to test it.
                var parities = new[]
                {
                    new Parity {
                        Name = "Even", UpdatedAt = now, UpdatedBy = "Måns"
                    },
                    new Parity {
                        Name = "Odd", UpdatedAt = now, UpdatedBy = "Måns"
                    },
                };
                db.BulkInsertAll(parities);

                Assert.IsTrue(parities[0].Id > 0);
                Assert.IsTrue(parities[1].Id > 0);
            }
        }
        public void BulkInsertingEntitiesUsingTablePerHierarchyShouldWorkWhenIgnoringGeneratedPrimaryKeys()
        {
            using (var db = new UnitTestsContext())
            {
                var warnings = new[]
                {
                    new LogWarning
                    {
                        Timestamp      = DateTime.Now,
                        Message        = "my warning message 1",
                        Recommendation = "my recommendation 1",
                        Id             = 0,
                    },
                    new LogWarning
                    {
                        Timestamp = DateTime.Now,
                        Message   = "my warning message 2",
                        Id        = 0,
                    },
                    new LogWarning
                    {
                        Timestamp = DateTime.Now,
                        Message   = "my warning message 3",
                        Id        = 0,
                    }
                };

                var request1 = new BulkInsertRequest <LogWarning>
                {
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
                    EnableRecursiveInsert      = EnableRecursiveInsert.NoAndIgnoreGeneratedPrimaryKeys,
                    Entities = warnings
                };

                db.BulkInsertAll(request1);

                var dbWarnings = db.LogItems.OfType <LogWarning>()
                                 .OrderBy(item => item.Message)
                                 .ToArray();
                Assert.AreEqual(3, dbWarnings.Length);
                Assert.AreEqual("my warning message 1", dbWarnings[0].Message);
                Assert.AreEqual("my warning message 2", dbWarnings[1].Message);
                Assert.AreEqual("my warning message 3", dbWarnings[2].Message);

                var errors = new[]
                {
                    new LogError
                    {
                        Timestamp = DateTime.Now,
                        Message   = "my error message 1",
                        Severity  = 1,
                        Id        = 0,
                    },
                    new LogError
                    {
                        Timestamp = DateTime.Now,
                        Message   = "my error message 2",
                        Severity  = 7,
                        Id        = 0,
                    },
                    new LogError
                    {
                        Timestamp = DateTime.Now,
                        Message   = "my error message 3",
                        Id        = 0,
                    }
                };

                var request2 = new BulkInsertRequest <LogError>
                {
                    AllowNotNullSelfReferences = AllowNotNullSelfReferences.No,
                    EnableRecursiveInsert      = EnableRecursiveInsert.NoAndIgnoreGeneratedPrimaryKeys,
                    Entities = errors
                };
                db.BulkInsertAll(request2);

                var dbErrors = db.LogItems.OfType <LogError>()
                               .OrderBy(item => item.Message)
                               .ToArray();
                Assert.AreEqual(3, dbErrors.Length);
                Assert.AreEqual("my error message 1", dbErrors[0].Message);
                Assert.AreEqual("my error message 2", dbErrors[1].Message);
                Assert.AreEqual("my error message 3", dbErrors[2].Message);
            }
        }