public async Task Creates_basic_database()
    {
        using var testDatabase = SqlServerTestStore.Create(StoreName + "Basic");
        using var context      = new BasicContext(testDatabase);
        await context.Database.EnsureDeletedAsync();

        await context.Database.EnsureCreatedAsync();

        await AssertOptionsAsync(context.Database.GetDbConnection(), 1L << 30, "Basic", "Basic");
    }
    public async Task Creates_database_in_elastic_pool()
    {
        using var testDatabase = SqlServerTestStore.Create(StoreName + "Elastic");
        using var context      = new ElasticPoolContext(testDatabase);
        await context.Database.EnsureDeletedAsync();

        await context.Database.EnsureCreatedAsync();

        await AssertOptionsAsync(context.Database.GetDbConnection(), 1000 *(1L << 28), "Standard", "ElasticPool");
    }
    public async Task Creates_business_critical_database()
    {
        using var testDatabase = SqlServerTestStore.Create(StoreName + "BusinessCritical");
        using var context      = new BusinessCriticalContext(testDatabase);
        await context.Database.EnsureDeletedAsync();

        await context.Database.EnsureCreatedAsync();

        await AssertOptionsAsync(context.Database.GetDbConnection(), 1L << 31, "BusinessCritical", "BC_Gen4_1");
    }
        public void Hidden_Column()
        {
            using (var scratch = SqlServerTestStore.Create("WithHiddenColumns"))
            {
                scratch.ExecuteNonQuery(@"
CREATE TABLE dbo.SystemVersioned
(
     Id int NOT NULL PRIMARY KEY CLUSTERED,
     Name varchar(50) NOT NULL,
     SysStartTime datetime2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
     SysEndTime datetime2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
     PERIOD FOR SYSTEM_TIME(SysStartTime, SysEndTime)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.History));
");

                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "SystemVersionedContext.cs",
                        "SystemVersioned.cs",
                    }
                };

                var filePaths = Generator.Generate(
                    scratch.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectDir + Path.DirectorySeparatorChar,
                    outputPath: null,     // not used for this test
                    rootNamespace: TestNamespace,
                    contextName: "SystemVersionedContext",
                    useDataAnnotations: false,
                    overwriteFiles: false,
                    useDatabaseNames: false);


                scratch.ExecuteNonQuery(@"
ALTER TABLE dbo.SystemVersioned SET (SYSTEM_VERSIONING = OFF);
DROP TABLE dbo.History;
");

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        private SqlServerTestStore GetTriggersTestStore()
        {
            var testStore = SqlServerTestStore.Create("SqlServerTriggers");

            using (var context = CreateTriggersContext(testStore))
            {
                context.Database.EnsureCreated();
            }

            testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_InsertProduct
ON Products
AFTER INSERT AS
BEGIN
	IF @@ROWCOUNT = 0
		return
	SET nocount on;

    INSERT INTO ProductBackups
    SELECT * FROM INSERTED;
END");

            testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_UpdateProduct
ON Products
AFTER UPDATE AS
BEGIN
	IF @@ROWCOUNT = 0
		return
	SET nocount on;

    UPDATE b
    SET b.Name = p.Name, b.Version = p.Version
    FROM ProductBackups b
    INNER JOIN Products p
        ON b.Id = p.Id
    WHERE p.Id IN(SELECT INSERTED.Id FROM INSERTED);
END");

            testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_DeleteProduct
ON Products
AFTER DELETE AS
BEGIN
	IF @@ROWCOUNT = 0
		return
	SET nocount on;

    DELETE FROM ProductBackups
    WHERE Id IN(SELECT DELETED.Id FROM DELETED);
END");
            return(testStore);
        }
        public async System.Threading.Tasks.Task Stream_Generate_Delete_For_Single_Entity()
        {
            using (var testDatabase = SqlServerTestStore.Create(DatabaseName))
            {
                var loggingFactory  = new TestSqlLoggerFactory();
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkSqlServer()
                                      .AddSingleton <ILoggerFactory>(loggingFactory)
                                      .BuildServiceProvider();

                var optionsBuilder = new DbContextOptionsBuilder()
                                     .EnableSensitiveDataLogging()
                                     .UseSqlServer(testDatabase.ConnectionString, b => b.ApplyConfiguration())
                                     .UseInternalServiceProvider(serviceProvider);

                using (var db = new BloggingContext(optionsBuilder.Options))
                {
                    await CreateBlogDatabaseAsync <Blog>(db);
                }

                loggingFactory.Clear();

                using (var db = new BloggingContext(optionsBuilder.Options))
                {
                    var toDelete = db.Blogs.Single(b => b.Name == "Blog2");
                    toDelete.Name = "Blog to delete";
                    var deletedId = toDelete.Id;


                    db.Entry(toDelete).State = EntityState.Deleted;

                    var statement = "";

                    using (var stream = new MemoryStream())
                    {
                        db.Generate(stream);
                        stream.Seek(0, SeekOrigin.Begin);
                        var streamReader = new StreamReader(stream);
                        statement = await streamReader.ReadToEndAsync();

                        Assert.IsTrue(!string.IsNullOrEmpty(statement));
                    }

                    var reader = new StringReader(statement);
                    IList <ParseError> errors;
                    var parser = new TSql140Parser(false);

                    var parseResult = parser.Parse(reader, out errors);

                    Assert.IsFalse(errors.Any());
                }
            }
        }
        public async System.Threading.Tasks.Task Generate_Insert_For_Single_Entity()
        {
            using (var testDatabase = SqlServerTestStore.Create(DatabaseName))
            {
                var loggingFactory  = new TestSqlLoggerFactory();
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkSqlServer()
                                      .AddSingleton <ILoggerFactory>(loggingFactory)
                                      .BuildServiceProvider();

                var optionsBuilder = new DbContextOptionsBuilder()
                                     .EnableSensitiveDataLogging()
                                     .UseSqlServer(testDatabase.ConnectionString, b => b.ApplyConfiguration())
                                     .UseInternalServiceProvider(serviceProvider);

                using (var db = new BloggingContext(optionsBuilder.Options))
                {
                    await CreateBlogDatabaseAsync <Blog>(db);
                }

                loggingFactory.Clear();

                using (var db = new BloggingContext(optionsBuilder.Options))
                {
                    var toAdd = db.Add(new Blog
                    {
                        Name       = "Blog to Insert",
                        George     = true,
                        TheGu      = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"),
                        NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777),
                        ToEat      = 64,
                        OrNothing  = 0.123456789,
                        Fuse       = 777,
                        WayRound   = 9876543210,
                        Away       = 0.12345f,
                        AndChew    = new byte[16]
                    }).Entity;

                    var statement = db.Generate();

                    var reader = new StringReader(statement);
                    IList <ParseError> errors;
                    var parser = new TSql140Parser(false);

                    var parseResult = parser.Parse(reader, out errors);

                    Assert.IsFalse(errors.Any());
                }
            }
        }
        public void Insert_with_non_key_default_value()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextNonKeyDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    var blogs = new List <Blog>
                    {
                        new Blog {
                            Name = "One Unicorn"
                        },
                        new Blog {
                            Name = "Two Unicorns", CreatedOn = new DateTime(1969, 8, 3, 0, 10, 0)
                        }
                    };

                    context.AddRange(blogs);

                    context.SaveChanges();

                    Assert.NotEqual(new DateTime(), blogs[0].CreatedOn);
                    Assert.NotEqual(new DateTime(), blogs[1].CreatedOn);
                    Assert.Null(blogs[0].OtherId);
                    Assert.Null(blogs[1].OtherId);
                }

                using (var context = new BlogContextNonKeyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Name).ToList();

                    Assert.NotEqual(new DateTime(), blogs[0].CreatedOn);
                    Assert.Equal(new DateTime(1969, 8, 3, 0, 10, 0), blogs[1].CreatedOn);

                    blogs[0].CreatedOn = new DateTime(1973, 9, 3, 0, 10, 0);
                    blogs[1].Name      = "Zwo Unicorns";

                    context.SaveChanges();
                }

                using (var context = new BlogContextNonKeyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Name).ToList();

                    Assert.Equal(new DateTime(1969, 8, 3, 0, 10, 0), blogs[1].CreatedOn);
                    Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 0), blogs[0].CreatedOn);
                }
            }
        }
Example #9
0
        public void Inserts_are_batched_correctly(bool clientPk, bool clientFk, bool clientOrder)
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                var options = new DbContextOptionsBuilder()
                              .UseSqlServer(testStore.Connection, b => b.ApplyConfiguration())
                              .UseInternalServiceProvider(
                    new ServiceCollection()
                    .AddEntityFrameworkSqlServer()
                    .BuildServiceProvider())
                              .Options;

                var expectedBlogs = new List <Blog>();
                using (var context = new BloggingContext(options))
                {
                    context.Database.EnsureClean();

                    var owner1 = new Owner();
                    var owner2 = new Owner();
                    context.Owners.Add(owner1);
                    context.Owners.Add(owner2);

                    for (var i = 1; i < 500; i++)
                    {
                        var blog = new Blog();
                        if (clientPk)
                        {
                            blog.Id = Guid.NewGuid();
                        }

                        if (clientFk)
                        {
                            blog.Owner = i % 2 == 0 ? owner1 : owner2;
                        }

                        if (clientOrder)
                        {
                            blog.Order = i;
                        }

                        context.Blogs.Add(blog);
                        expectedBlogs.Add(blog);
                    }

                    context.SaveChanges();
                }

                AssertDatabaseState(clientOrder, expectedBlogs, options);
            }
        }
        public void Non_null_boolean_columns_with_default_constraint_become_nullable_properties()
        {
            using (var scratch = SqlServerTestStore.Create("NonNullBooleanWithDefaultConstraint"))
            {
                scratch.ExecuteNonQuery(@"
CREATE TABLE NonNullBoolWithDefault
(
     Id int NOT NULL PRIMARY KEY CLUSTERED,
     BoolWithDefaultValueSql bit NOT NULL DEFAULT (CONVERT(""bit"", GETDATE())),
     BoolWithoutDefaultValueSql bit NOT NULL
)");

                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "NonNullBoolWithDefaultContext.cs",
                        "NonNullBoolWithDefault.cs",
                    }
                };

                var filePaths = Generator.Generate(
                    scratch.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectDir + Path.DirectorySeparatorChar,
                    outputPath: null,     // not used for this test
                    rootNamespace: TestNamespace,
                    contextName: "NonNullBoolWithDefaultContext",
                    useDataAnnotations: false,
                    overwriteFiles: false,
                    useDatabaseNames: false);


                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                Assert.Contains("warn: " + DesignStrings.NonNullableBoooleanColumnHasDefaultConstraint("dbo.NonNullBoolWithDefault.BoolWithDefaultValueSql"), _reporter.Messages);
                Assert.Equal(1, _reporter.Messages.Count(m => m.StartsWith("warn: ")));

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public void PrimaryKeyWithSequence()
        {
            using (var scratch = SqlServerTestStore.Create("SqlServerE2E"))
            {
                scratch.ExecuteNonQuery(@"
CREATE SEQUENCE PrimaryKeyWithSequenceSequence
    AS int
    START WITH 1
    INCREMENT BY 1

CREATE TABLE PrimaryKeyWithSequence (
    PrimaryKeyWithSequenceId int DEFAULT(NEXT VALUE FOR PrimaryKeyWithSequenceSequence),
    PRIMARY KEY (PrimaryKeyWithSequenceId)
);
");

                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "PrimaryKeyWithSequenceContext.cs",
                        "PrimaryKeyWithSequence.cs"
                    }
                };

                var filePaths = Generator.Generate(
                    scratch.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectDir + Path.DirectorySeparatorChar,
                    outputPath: null,     // not used for this test
                    rootNamespace: TestNamespace,
                    contextName: "PrimaryKeyWithSequenceContext",
                    useDataAnnotations: false,
                    overwriteFiles: false,
                    useDatabaseNames: false);

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public void Insert_with_non_key_default_value_readonly()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.AddRange(
                        new Blog {
                        Name = "One Unicorn"
                    },
                        new Blog {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();

                    Assert.NotEqual(new DateTime(), context.Blogs.ToList()[0].CreatedOn);
                }

                DateTime dateTime0;

                using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    dateTime0 = blogs[0].CreatedOn;

                    Assert.NotEqual(new DateTime(), dateTime0);
                    Assert.NotEqual(new DateTime(), blogs[1].CreatedOn);

                    blogs[0].Name      = "One Pegasus";
                    blogs[1].CreatedOn = new DateTime(1973, 9, 3, 0, 10, 0);

                    context.SaveChanges();
                }

                using (var context = new BlogContextNonKeyReadOnlyDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(dateTime0, blogs[0].CreatedOn);
                    Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 0), blogs[1].CreatedOn);
                }
            }
        }
        public void Index_with_filter()
        {
            using (var scratch = SqlServerTestStore.Create("SqlServerE2E"))
            {
                scratch.ExecuteNonQuery(@"
CREATE TABLE FilteredIndex (
    Id int,
    Number int,
    PRIMARY KEY (Id)
);

CREATE INDEX Unicorn_Filtered_Index
    ON FilteredIndex (Number) WHERE Number > 10
");

                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "FilteredIndexContext.cs",
                        "FilteredIndex.cs",
                    }
                };

                var filePaths = Generator.Generate(
                    scratch.ConnectionString,
                    Enumerable.Empty <string>(),
                    Enumerable.Empty <string>(),
                    TestProjectDir + Path.DirectorySeparatorChar,
                    outputPath: null,     // not used for this test
                    rootNamespace: TestNamespace,
                    contextName: "FilteredIndexContext",
                    useDataAnnotations: false,
                    overwriteFiles: false,
                    useDatabaseNames: false);

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public void Insert_with_default_value_from_sequence()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.AddRange(new Blog {
                        Name = "One Unicorn"
                    }, new Blog {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextDefaultValue(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(77, blogs[0].Id);
                    Assert.Equal(78, blogs[1].Id);
                }

                using (var context = new BlogContextDefaultValueNoMigrations(testStore.Name))
                {
                    context.AddRange(new Blog {
                        Name = "One Unicorn"
                    }, new Blog {
                        Name = "Two Unicorns"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContextDefaultValueNoMigrations(testStore.Name))
                {
                    var blogs = context.Blogs.OrderBy(e => e.Id).ToList();

                    Assert.Equal(77, blogs[0].Id);
                    Assert.Equal(78, blogs[1].Id);
                    Assert.Equal(79, blogs[2].Id);
                    Assert.Equal(80, blogs[3].Id);
                }
            }
        }
Example #15
0
        public void PrimaryKeyWithSequence()
        {
            using (var scratch = SqlServerTestStore.Create("SqlServerE2E"))
            {
                scratch.ExecuteNonQuery(@"
CREATE SEQUENCE PrimaryKeyWithSequenceSequence
    AS int
    START WITH 1
    INCREMENT BY 1

CREATE TABLE PrimaryKeyWithSequence (
    PrimaryKeyWithSequenceId int DEFAULT(NEXT VALUE FOR PrimaryKeyWithSequenceSequence),
    PRIMARY KEY (PrimaryKeyWithSequenceId)
);
");

                var configuration = new ReverseEngineeringConfiguration
                {
                    ConnectionString     = scratch.ConnectionString,
                    ProjectPath          = TestProjectDir + Path.DirectorySeparatorChar,
                    ProjectRootNamespace = TestNamespace,
                    ContextClassName     = "PrimaryKeyWithSequenceContext",
                    UseFluentApiOnly     = true
                };
                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "PrimaryKeyWithSequenceContext.expected",
                        "PrimaryKeyWithSequence.expected"
                    }
                };

                var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        private static async Task Returns_false_when_database_does_not_exist_test(bool async, bool ambientTransaction, bool file)
        {
            using (var testDatabase = SqlServerTestStore.Create("NonExisting", file))
            {
                using (var context = new BloggingContext(testDatabase))
                {
                    var creator = GetDatabaseCreator(context);

                    using (CreateTransactionScope(ambientTransaction))
                    {
                        Assert.False(async ? await creator.ExistsAsync() : creator.Exists());
                    }

                    Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
                }
            }
        }
Example #17
0
        public void Index_with_filter()
        {
            using (var scratch = SqlServerTestStore.Create("SqlServerE2E"))
            {
                scratch.ExecuteNonQuery(@"
CREATE TABLE FilteredIndex (
    Id int,
    Number int,
    PRIMARY KEY (Id)
);

CREATE INDEX Unicorn_Filtered_Index
    ON FilteredIndex (Number) WHERE Number > 10
");

                var configuration = new ReverseEngineeringConfiguration
                {
                    ConnectionString     = scratch.ConnectionString,
                    ProjectPath          = TestProjectDir + Path.DirectorySeparatorChar,
                    ProjectRootNamespace = TestNamespace,
                    ContextClassName     = "FilteredIndexContext",
                    UseFluentApiOnly     = true
                };
                var expectedFileSet = new FileSet(new FileSystemFileService(),
                                                  Path.Combine("ReverseEngineering", "Expected"),
                                                  contents => contents.Replace("{{connectionString}}", scratch.ConnectionString))
                {
                    Files = new List <string>
                    {
                        "FilteredIndexContext.expected",
                        "FilteredIndex.expected",
                    }
                };

                var filePaths = Generator.GenerateAsync(configuration).GetAwaiter().GetResult();

                var actualFileSet = new FileSet(InMemoryFiles, Path.GetFullPath(TestProjectDir))
                {
                    Files = new[] { filePaths.ContextFile }.Concat(filePaths.EntityTypeFiles).Select(Path.GetFileName).ToList()
                };

                AssertEqualFileContents(expectedFileSet, actualFileSet);
                AssertCompile(actualFileSet);
            }
        }
        public override TestStore CreateTestStore(Type testStoreType)
        {
            if (testStoreType == typeof(InMemoryTestStore))
            {
                return(new InMemoryTestStore());
            }

            if (testStoreType == typeof(SqlServerTestStore))
            {
                return(SqlServerTestStore.Create("SharedCrossStore"));
            }

            if (testStoreType == typeof(SqliteTestStore))
            {
                return(SqliteTestStore.CreateScratch());
            }

            throw new NotImplementedException();
        }
        public void Insert_with_ValueGeneratedOnAdd_GUID_nonkey_property_throws()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextClientGuidNonKey(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    var blog = context.Add(new GuidBlog {
                        Name = "One Unicorn"
                    }).Entity;

                    Assert.Equal(default(Guid), blog.NotId);

                    // No value set on a required column
                    Assert.Throws <DbUpdateException>(() => context.SaveChanges());
                }
            }
        }
        public void Resolve_concurreny()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextConcurrencyWithRowversion(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    var blog = context.Add(new ConcurrentBlog {
                        Name = "One Unicorn"
                    }).Entity;

                    context.SaveChanges();

                    using (var innerContext = new BlogContextConcurrencyWithRowversion(testStore.Name))
                    {
                        var updatedBlog = innerContext.ConcurrentBlogs.Single();
                        updatedBlog.Name = "One Pegasus";
                        innerContext.SaveChanges();
                        var currentTimestamp = updatedBlog.Timestamp.ToArray();

                        try
                        {
                            blog.Name = "One Earth Pony";
                            context.SaveChanges();
                        }
                        catch (DbUpdateConcurrencyException)
                        {
                            // Update origianal values (and optionally any current values)
                            // Would normally do this with just one method call
                            context.Entry(blog).Property(e => e.Id).OriginalValue        = updatedBlog.Id;
                            context.Entry(blog).Property(e => e.Name).OriginalValue      = updatedBlog.Name;
                            context.Entry(blog).Property(e => e.Timestamp).OriginalValue = updatedBlog.Timestamp;

                            context.SaveChanges();

                            Assert.NotEqual(blog.Timestamp, currentTimestamp);
                        }
                    }
                }
            }
        }
        public async System.Threading.Tasks.Task Generate_Update_For_Single_Entity()
        {
            using (var testDatabase = SqlServerTestStore.Create(DatabaseName))
            {
                var loggingFactory  = new TestSqlLoggerFactory();
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkSqlServer()
                                      .AddSingleton <ILoggerFactory>(loggingFactory)
                                      .BuildServiceProvider();

                var optionsBuilder = new DbContextOptionsBuilder()
                                     .EnableSensitiveDataLogging()
                                     .UseSqlServer(testDatabase.ConnectionString, b => b.ApplyConfiguration())
                                     .UseInternalServiceProvider(serviceProvider);

                using (var db = new BloggingContext(optionsBuilder.Options))
                {
                    await CreateBlogDatabaseAsync <Blog>(db);
                }

                loggingFactory.Clear();

                using (var db = new BloggingContext(optionsBuilder.Options))
                {
                    var toUpdate = db.Blogs.Single(b => b.Name == "Blog1");
                    toUpdate.Name = "Blog is Updated";
                    var updatedId = toUpdate.Id;

                    db.Entry(toUpdate).State = EntityState.Modified;

                    var statement = db.Generate();

                    var reader = new StringReader(statement);
                    IList <ParseError> errors;
                    var parser = new TSql140Parser(false);

                    var parseResult = parser.Parse(reader, out errors);

                    Assert.IsFalse(errors.Any());
                }
            }
        }
Example #22
0
        public OneToOneQuerySqlServerFixture()
        {
            _testStore = SqlServerTestStore.Create("OneToOneQueryTest");

            _options = new DbContextOptionsBuilder()
                       .UseSqlServer(_testStore.ConnectionString, b => b.ApplyConfiguration())
                       .UseInternalServiceProvider(new ServiceCollection()
                                                   .AddEntityFrameworkSqlServer()
                                                   .AddSingleton(TestModelSource.GetFactory(OnModelCreating))
                                                   .AddSingleton <ILoggerFactory>(TestSqlLoggerFactory)
                                                   .BuildServiceProvider(validateScopes: true))
                       .Options;

            using (var context = new DbContext(_options))
            {
                context.Database.EnsureCreated();

                AddTestData(context);
            }
        }
        public void Insert_explicit_value_into_computed_column()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextComputedColumn(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.Add(new FullNameBlog {
                        FirstName = "One", LastName = "Unicorn", FullName = "Gerald"
                    });

                    // The property 'FullName' on entity type 'FullNameBlog' is defined to be read-only before it is
                    // saved, but its value has been set to something other than a temporary or default value.
                    Assert.Equal(
                        CoreStrings.PropertyReadOnlyBeforeSave("FullName", "FullNameBlog"),
                        Assert.Throws <InvalidOperationException>(() => context.SaveChanges()).Message);
                }
            }
        }
Example #24
0
        public BuiltInDataTypesSqlServerFixture()
        {
            _testStore = SqlServerTestStore.Create("BuiltInDataTypes");

            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkSqlServer()
                                  .AddSingleton(TestModelSource.GetFactory(OnModelCreating))
                                  .AddSingleton <ILoggerFactory>(TestSqlLoggerFactory)
                                  .BuildServiceProvider();

            _options = new DbContextOptionsBuilder()
                       .UseSqlServer(_testStore.Connection, b => b.ApplyConfiguration())
                       .EnableSensitiveDataLogging()
                       .UseInternalServiceProvider(serviceProvider)
                       .Options;

            using (var context = new DbContext(_options))
            {
                context.Database.EnsureCreated();
            }
        }
        public void Insert_and_update_with_computed_column_with_function()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextComputedColumnWithFunction(testStore.Name))
                {
                    context.Database.ExecuteSqlCommand
                        (@"CREATE FUNCTION
[dbo].[GetFullName](@First NVARCHAR(MAX), @Second NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) WITH SCHEMABINDING AS BEGIN RETURN @First + @Second END");

                    context.GetService <IRelationalDatabaseCreator>().CreateTables();
                }

                using (var context = new BlogContextComputedColumnWithFunction(testStore.Name))
                {
                    var blog = context.Add(new FullNameBlog {
                        FirstName = "One", LastName = "Unicorn"
                    }).Entity;

                    context.SaveChanges();

                    Assert.Equal("OneUnicorn", blog.FullName);
                }

                using (var context = new BlogContextComputedColumnWithFunction(testStore.Name))
                {
                    var blog = context.FullNameBlogs.Single();

                    Assert.Equal("OneUnicorn", blog.FullName);

                    blog.LastName = "Pegasus";

                    context.SaveChanges();

                    Assert.Equal("OnePegasus", blog.FullName);
                }
            }
        }
Example #26
0
        public void It_creates_unique_query_cache_key()
        {
            using (var testStore = SqlServerTestStore.Create(nameof(CompiledQueryCacheKeyGeneratorTest)))
            {
                object     key1, key2;
                Expression query;
                using (var context1 = new QueryKeyCacheContext(rowNumberPaging: true, connection: testStore.Connection))
                {
                    var generator = context1.GetService <ICompiledQueryCacheKeyGenerator>();
                    query = context1.Set <Poco1>().Skip(4).Take(10).Expression;
                    key1  = generator.GenerateCacheKey(query, false);
                }

                using (var context2 = new QueryKeyCacheContext(rowNumberPaging: false, connection: testStore.Connection))
                {
                    var generator = context2.GetService <ICompiledQueryCacheKeyGenerator>();
                    key2 = generator.GenerateCacheKey(query, false);
                }

                Assert.NotEqual(key1, key2);
            }
        }
        public void Insert_explicit_value_throws_when_readonly_sequence_before_save()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContextReadOnlySequenceKeyColumnWithDefaultValue(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.AddRange(new Blog {
                        Id = 1, Name = "One Unicorn"
                    }, new Blog {
                        Name = "Two Unicorns"
                    });

                    // The property 'Id' on entity type 'Blog' is defined to be read-only before it is
                    // saved, but its value has been set to something other than a temporary or default value.
                    Assert.Equal(
                        CoreStrings.PropertyReadOnlyBeforeSave("Id", "Blog"),
                        Assert.Throws <InvalidOperationException>(() => context.SaveChanges()).Message);
                }
            }
        }
        public void Insert_with_explicit_default_keys()
        {
            using (var testStore = SqlServerTestStore.Create(DatabaseName))
            {
                using (var context = new BlogContext(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    context.AddRange(new Blog {
                        Id = 0, Name = "One Unicorn"
                    }, new Blog {
                        Id = 1, Name = "Two Unicorns"
                    });

                    // DbUpdateException : An error occurred while updating the entries. See the
                    // inner exception for details.
                    // SqlException : Cannot insert explicit value for identity column in table
                    // 'Blog' when IDENTITY_INSERT is set to OFF.
                    Assert.Throws <DbUpdateException>(() => context.SaveChanges());
                }
            }
        }
        private static async Task Noop_when_database_does_not_exist_test(bool async, bool file)
        {
            using var testDatabase = SqlServerTestStore.Create("NonExisting", file);
            using var context      = new BloggingContext(testDatabase);
            var creator = GetDatabaseCreator(context);

            Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

            if (async)
            {
                Assert.False(await creator.EnsureDeletedAsync());
            }
            else
            {
                Assert.False(creator.EnsureDeleted());
            }

            Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);

            Assert.False(async ? await creator.ExistsAsync() : creator.Exists());

            Assert.Equal(ConnectionState.Closed, context.Database.GetDbConnection().State);
        }
        private SqlServerTestStore GetQueryTriggersTestStore()
        {
            var testStore = SqlServerTestStore.Create("SqlServerTriggers");

            using (var context = CreateQueryTriggersContext(testStore))
            {
                context.Database.EnsureCreated();
            }

            testStore.ExecuteNonQuery(@"
CREATE TRIGGER TRG_InsertUpdateProduct
ON UpdatedProducts
AFTER INSERT, UPDATE AS
BEGIN
	IF @@ROWCOUNT = 0
		return
	SET nocount on;

    UPDATE UpdatedProducts set StoreUpdated = StoreUpdated + 1
    WHERE Id IN(SELECT INSERTED.Id FROM INSERTED);
END");
            return(testStore);
        }