Example #1
0
                public SimpleProject()
                {
                    var source = new BuildSource
                    {
                        TargetDir  = TargetDir,
                        References =
                        {
                            BuildReference.ByName("System.Diagnostics.DiagnosticSource",                                             copyLocal: true),
                            BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                            BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                            BuildReference.ByName("Microsoft.AspNetCore.Hosting.Abstractions",                                       copyLocal: true),
                            BuildReference.ByName("Microsoft.EntityFrameworkCore",                                                   copyLocal: true),
                            BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools",                                             copyLocal: true),
                            BuildReference.ByName("Microsoft.EntityFrameworkCore.Design.Core",                                       copyLocal: true),
                            BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",                                        copyLocal: true),
                            BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational.Design",                                 copyLocal: true),
                            BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",                                         copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",                                       copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                                             copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",                                 copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.DependencyInjection",                                        copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions",                           copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.FileProviders.Abstractions",                                 copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.Logging",                                                    copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",                                       copyLocal: true),
                            BuildReference.ByName("Microsoft.Extensions.Options",                                                    copyLocal: true),
                            BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                        },
                        Sources = { @"
                            using Microsoft.EntityFrameworkCore;
                            using Microsoft.EntityFrameworkCore.Infrastructure;
                            using Microsoft.EntityFrameworkCore.Migrations;

                            namespace SimpleProject
                            {
                                internal class SimpleContext : DbContext
                                {
                                    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                    {
                                        optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SimpleProject.SimpleContext;Integrated Security=True"");
                                    }
                                }

                                namespace Migrations
                                {
                                    [DbContext(typeof(SimpleContext))]
                                    [Migration(""20141010222726_InitialCreate"")]
                                    public class InitialCreate : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }" }
                    };
                    var build = source.Build();

                    Executor = new AppDomainOperationExecutor(TargetDir, build.TargetName, TargetDir, TargetDir, "SimpleProject");
                }
        private ModelSnapshot CompileModelSnapshot(string modelSnapshotCode, string modelSnapshotTypeName)
        {
            var build = new BuildSource
            {
                References =
                {
#if NET452
                    BuildReference.ByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                    BuildReference.ByName("System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
#else
                    BuildReference.ByName("System.Text.RegularExpressions"),
#endif
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Design.Tests"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational")
                },
                Sources = { modelSnapshotCode }
            };

            var assembly = build.BuildInMemory();

            var snapshotType = assembly.GetType(modelSnapshotTypeName, throwOnError: true, ignoreCase: false);

            var contextTypeAttribute = snapshotType.GetTypeInfo().GetCustomAttribute <DbContextAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            return((ModelSnapshot)Activator.CreateInstance(snapshotType));
        }
Example #3
0
        protected void Test(
            Action <ModelBuilder> buildModel,
            ModelCodeGenerationOptions options,
            Action <ScaffoldedModel> assertScaffold,
            Action <IModel> assertModel)
        {
            var modelBuilder = SqlServerTestHelpers.Instance.CreateConventionBuilder();

            modelBuilder.Model.RemoveAnnotation(CoreAnnotationNames.ProductVersion);
            buildModel(modelBuilder);

            var model = modelBuilder.FinalizeModel();

            var services = new ServiceCollection()
                           .AddEntityFrameworkDesignTimeServices();

            new SqlServerDesignTimeServices().ConfigureDesignTimeServices(services);

            var generator = services
                            .BuildServiceProvider()
                            .GetRequiredService <IModelCodeGenerator>();

            options.ModelNamespace ??= "TestNamespace";
            options.ContextName      = "TestDbContext";
            options.ConnectionString = "Initial Catalog=TestDatabase";

            var scaffoldedModel = generator.GenerateModel(
                model,
                options);

            assertScaffold(scaffoldedModel);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer")
                },
                Sources = new List <string>(
                    new[] { scaffoldedModel.ContextFile.Code }.Concat(
                        scaffoldedModel.AdditionalFiles.Select(f => f.Code)))
            };

            var assembly         = build.BuildInMemory();
            var contextNamespace = options.ContextNamespace ?? options.ModelNamespace;
            var context          = (DbContext)assembly.CreateInstance(
                !string.IsNullOrEmpty(contextNamespace)
                    ? contextNamespace + "." + options.ContextName
                    : options.ContextName);

            if (assertModel != null)
            {
                var compiledModel = context.Model;
                assertModel(compiledModel);
            }
        }
        protected override ICollection <BuildReference> GetReferences()
        {
            var references = base.GetReferences();

            references.Add(BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer"));

            return(references);
        }
Example #5
0
        private void Test(Action <ModelBuilder> buildModel, string expectedCode, Action <IModel> assert)
        {
            var modelBuilder = TestHelpers.Instance.CreateConventionBuilder();

            buildModel(modelBuilder);
            var model = modelBuilder.Model;

            var generator = new CSharpModelGenerator(new CSharpHelper());

            var builder = new IndentedStringBuilder();

            generator.Generate(model, builder);
            var code = builder.ToString();

            Assert.Equal(expectedCode, code);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                    BuildReference.ByName("System.Linq.Expressions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                    BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                    BuildReference.ByName("EntityFramework.Core"),
                    BuildReference.ByName("EntityFramework.Relational")
                },
                Sources = { @"
                    using System;
                    using Microsoft.Data.Entity;
                    using Microsoft.Data.Entity.Metadata;
                    using Microsoft.Data.Entity.Metadata.Conventions;
                    using Microsoft.Data.Entity.Migrations.Infrastructure;


                    public static class ModelSnapshot
                    {
                        public static IModel Model
                        {
                            get
                            {
                                var builder = new ModelBuilder(new ConventionSet());
                                " + code + @"

                                return builder.Model;
                            }
                        }
                   }
                " }
            };

            var assembly    = build.BuildInMemory();
            var factoryType = assembly.GetType("ModelSnapshot");
            var property    = factoryType.GetProperty("Model");
            var value       = (IModel)property.GetValue(null);

            Assert.NotNull(value);
            assert(value);
        }
                public SimpleProject()
                {
                    var source = new BuildSource
                    {
                        TargetDir  = TargetDir,
                        References =
                        {
                            BuildReference.ByName("System.Collections.Immutable",                                                    copyLocal: true),
                            BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                            BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                            BuildReference.ByName("EntityFramework.Core",                                                            copyLocal: true),
                            BuildReference.ByName("EntityFramework.Commands",                                                        copyLocal: true),
                            BuildReference.ByName("EntityFramework.Relational",                                                      copyLocal: true),
                            BuildReference.ByName("EntityFramework.Relational.Design",                                               copyLocal: true),
                            BuildReference.ByName("EntityFramework.SqlServer",                                                       copyLocal: true),
                            BuildReference.ByName("Microsoft.CodeAnalysis",                                                          copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.Caching.Abstractions",                                        copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.Caching.Memory",                                              copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.DependencyInjection",                                         copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.DependencyInjection.Abstractions",                            copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.Logging",                                                     copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.Logging.Abstractions",                                        copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.OptionsModel",                                                copyLocal: true),
                            BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                        },
                        Sources = { @"
                            using Microsoft.Data.Entity;
                            using Microsoft.Data.Entity.Infrastructure;
                            using Microsoft.Data.Entity.Migrations;

                            namespace SimpleProject
                            {
                                internal class SimpleContext : DbContext
                                {
                                    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                    {
                                        optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SimpleProject.SimpleContext;Integrated Security=True"");
                                    }
                                }

                                namespace Migrations
                                {
                                    [DbContext(typeof(SimpleContext))]
                                    public class InitialCreate : Migration
                                    {
                                        public override string Id => ""201410102227260_InitialCreate"";

                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }" }
                    };
                    var build = source.Build();

                    Executor = new ExecutorWrapper(TargetDir, build.TargetName + ".dll", TargetDir, "SimpleProject");
                }
        public void Snapshots_compile()
        {
            var codeHelper = new CSharpHelper();
            var generator  = new CSharpMigrationGenerator(
                codeHelper,
                new CSharpMigrationOperationGenerator(codeHelper),
                new CSharpModelGenerator(codeHelper));

            var modelSnapshotCode = generator.GenerateSnapshot("MyNamespace", typeof(MyContext), "MySnapshot", new Model());

            Assert.Equal(@"using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Microsoft.Data.Entity.Commands.Migrations;

namespace MyNamespace
{
    [ContextType(typeof(CodeCompilationTest.MyContext))]
    partial class MySnapshot : ModelSnapshot
    {
        public override void BuildModel(ModelBuilder builder)
        {
        }
    }
}
", modelSnapshotCode);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName(typeof(CodeCompilationTest).Assembly.GetName().Name),
                    BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                    BuildReference.ByName("EntityFramework.Core"),
                    BuildReference.ByName("EntityFramework.Relational")
                },
                Sources = { modelSnapshotCode }
            };

            var assembly = build.BuildInMemory();

            var snapshotType = assembly.GetType("MyNamespace.MySnapshot", throwOnError: true);

            var contextTypeAttribute = snapshotType.GetCustomAttribute <ContextTypeAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType);

            var conventions  = new ConventionSet();
            var modelBuilder = new ModelBuilder(conventions);

            snapshot.BuildModel(modelBuilder);
            Assert.Empty(modelBuilder.Model.EntityTypes);
        }
Example #8
0
        public void Throws_for_no_parameterless_constructor()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Diagnostics.DiagnosticSource",                                             copyLocal: true),
                        BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                        BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                        BuildReference.ByName("Microsoft.AspNetCore.Hosting.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                                                   copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools.Core",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational.Design",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",                                         copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions",                           copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.FileProviders.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.PlatformAbstractions",                                       copyLocal: true),
                        BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                    },
                    Sources = { @"
                            using Microsoft.EntityFrameworkCore;
                            using Microsoft.EntityFrameworkCore.Infrastructure;
                            using Microsoft.EntityFrameworkCore.Migrations;

                            namespace MyProject
                            {
                                internal class MyContext : DbContext
                                {
                                    public MyContext(DbContextOptions<MyContext> options) :base(options)  {}
                                }
                            }" }
                };
                var build = source.Build();
                using (var executor = new AppDomainOperationExecutor(targetDir, build.TargetName, targetDir, targetDir, "MyProject"))
                {
                    var ex = Assert.Throws <OperationException>(
                        () => executor.GetMigrations("MyContext"));

                    Assert.Equal(
                        ToolsCoreStrings.NoParameterlessConstructor("MyContext"),
                        ex.Message);
                }
            }
        }
Example #9
0
        protected void Test(
            Action <ModelBuilder> buildModel,
            ModelCodeGenerationOptions options,
            Action <ScaffoldedModel> assertScaffold,
            Action <IModel> assertModel)
        {
            var modelBuilder = new ModelBuilder(BuildNonValidatingConventionSet());

            modelBuilder.Model.RemoveAnnotation(CoreAnnotationNames.ProductVersionAnnotation);
            buildModel(modelBuilder);
            var _ = modelBuilder.Model.Scaffolding().EntityTypeErrors;

            var model = modelBuilder.FinalizeModel();

            var services = new ServiceCollection()
                           .AddEntityFrameworkDesignTimeServices();

            new SqlServerDesignTimeServices().ConfigureDesignTimeServices(services);

            var generator = services
                            .BuildServiceProvider()
                            .GetRequiredService <IModelCodeGenerator>();

            var scaffoldedModel = generator.GenerateModel(
                model,
                "TestNamespace",
                "TestNamespace",
                "TestNamespace",
                /*contextDir:*/ string.Empty,
                "TestDbContext",
                "Initial Catalog=TestDatabase",
                options);

            assertScaffold(scaffoldedModel);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer")
                },
                Sources = new List <string>(
                    new[] { scaffoldedModel.ContextFile.Code }.Concat(
                        scaffoldedModel.AdditionalFiles.Select(f => f.Code)))
            };

            var assembly      = build.BuildInMemory();
            var context       = (DbContext)assembly.CreateInstance("TestNamespace.TestDbContext");
            var compiledModel = context.Model;

            assertModel(compiledModel);
        }
Example #10
0
        private void Test(
            Action <ModelBuilder> buildModel,
            ModelCodeGenerationOptions options,
            Action <ScaffoldedModel> assertScaffold,
            Action <IModel> assertModel)
        {
            var modelBuilder = new ModelBuilder(SqlServerConventionSetBuilder.Build());

            buildModel(modelBuilder);
            modelBuilder.GetInfrastructure().Metadata.Validate();

            var model = modelBuilder.Model;

            var services = new ServiceCollection()
                           .AddEntityFrameworkDesignTimeServices();

            new SqlServerDesignTimeServices().ConfigureDesignTimeServices(services);

            var generator = services
                            .BuildServiceProvider()
                            .GetRequiredService <IModelCodeGenerator>();

            var scaffoldedModel = generator.GenerateModel(
                model,
                "TestNamespace",
                /*contextDir:*/ string.Empty,
                "TestDbContext",
                "Initial Catalog=TestDatabase",
                options);

            assertScaffold(scaffoldedModel);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer")
                },
                Sources = new List <string>(
                    Enumerable.Concat(
                        new[] { scaffoldedModel.ContextFile.Code },
                        scaffoldedModel.AdditionalFiles.Select(f => f.Code)))
            };

            var assembly      = build.BuildInMemory();
            var context       = (DbContext)assembly.CreateInstance("TestNamespace.TestDbContext");
            var compiledModel = context.Model;

            assertModel(compiledModel);
        }
Example #11
0
        public void Throws_for_no_parameterless_constructor()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Threading.Tasks.Extensions",                     true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                         true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions",            true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Design",                  true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",              true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",              true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions", true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                          true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",             true)
                    },
                    Sources =
                    {
                        @"
                            using Microsoft.EntityFrameworkCore;
                            using Microsoft.EntityFrameworkCore.Infrastructure;
                            using Microsoft.EntityFrameworkCore.Migrations;

                            namespace MyProject
                            {
                                internal class MyContext : DbContext
                                {
                                    public MyContext(DbContextOptions<MyContext> options) :base(options)  {}
                                }
                            }"
                    }
                };
                var build = source.Build();
                using (var executor = CreateExecutorFromBuildResult(build, "MyProject", "C#"))
                {
                    var ex = Assert.Throws <WrappedException>(
                        () => executor.GetMigrations("MyContext"));

                    Assert.Equal(
                        DesignStrings.NoParameterlessConstructor("MyContext"),
                        ex.Message);
                }
            }
        }
Example #12
0
    private Assembly Compile(string assemblyCode)
    {
        var build = new BuildSource
        {
            References =
            {
                BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                BuildReference.ByName("Microsoft.EntityFrameworkCore.Design.Tests"),
                BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
                BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer"),
                BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite"),
                BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions")
            },
            Sources = { { "Startup.cs", assemblyCode } }
        };

        return(build.BuildInMemory());
    }
Example #13
0
        private ModelSnapshot CompileModelSnapshot(string modelSnapshotCode, string modelSnapshotTypeName)
        {
            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Design.Tests"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational")
                },
                Sources = { modelSnapshotCode }
            };

            var assembly = build.BuildInMemory();

            var snapshotType = assembly.GetType(modelSnapshotTypeName, throwOnError: true, ignoreCase: false);

            var contextTypeAttribute = snapshotType.GetTypeInfo().GetCustomAttribute <DbContextAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            return((ModelSnapshot)Activator.CreateInstance(snapshotType));
        }
Example #14
0
        public void AddMigration_begins_new_namespace_when_foreign_migrations()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Diagnostics.DiagnosticSource",                                             copyLocal: true),
                        BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                        BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                        BuildReference.ByName("Microsoft.AspNetCore.Hosting.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                                                   copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools.Core",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational.Design",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",                                         copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions",                           copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.FileProviders.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.PlatformAbstractions",                                       copyLocal: true),
                        BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                    },
                    Sources = { @"
                            using Microsoft.EntityFrameworkCore;
                            using Microsoft.EntityFrameworkCore.Infrastructure;
                            using Microsoft.EntityFrameworkCore.Migrations;

                            namespace MyProject
                            {
                                internal class MyFirstContext : DbContext
                                {
                                    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                    {
                                        optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyProject.MyFirstContext"");
                                    }
                                }

                                internal class MySecondContext : DbContext
                                {
                                    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                    {
                                        optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyProject.MySecondContext"");
                                    }
                                }

                                namespace Migrations
                                {
                                    [DbContext(typeof(MyFirstContext))]
                                    [Migration(""20151006140723_InitialCreate"")]
                                    public class InitialCreate : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }" }
                };
                var build = source.Build();
                using (var executor = new AppDomainOperationExecutor(targetDir, build.TargetName, targetDir, targetDir, "MyProject"))
                {
                    var artifacts = executor.AddMigration("MyMigration", /*outputDir:*/ null, "MySecondContext");
                    Assert.Equal(3, artifacts.Keys.Count);
                    Assert.True(Directory.Exists(Path.Combine(targetDir, @"Migrations\MySecond")));
                }
            }
        }
Example #15
0
        public void GetContextType_works_with_multiple_assemblies()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir      = directory.Path;
                var contextsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",             copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools",       copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools.Core",  copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions", copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions", copyLocal: true)
                    },
                    Sources = { @"
                        using Microsoft.EntityFrameworkCore;

                        namespace MyProject
                        {
                            public class Context1 : DbContext
                            {
                            }

                            public class Context2 : DbContext
                            {
                            }
                        }" }
                };
                var contextsBuild    = contextsSource.Build();
                var migrationsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Reflection.Metadata",                            copyLocal: true),
                        BuildReference.ByName("Microsoft.AspNetCore.Hosting.Abstractions",             copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",              copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational.Design",       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",             copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",              copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions", copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.FileProviders.Abstractions",       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                          copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",             copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                          copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.PlatformAbstractions",             copyLocal: true),
                        BuildReference.ByPath(contextsBuild.TargetPath)
                    },
                    Sources = { @"
                        using Microsoft.EntityFrameworkCore;
                        using Microsoft.EntityFrameworkCore.Infrastructure;
                        using Microsoft.EntityFrameworkCore.Migrations;

                        namespace MyProject
                        {
                            internal class Context3 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [DbContext(typeof(Context1))]
                                    [Migration(""000000000000000_Context1Migration"")]
                                    public class Context1Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [DbContext(typeof(Context2))]
                                    [Migration(""000000000000000_Context2Migration"")]
                                    public class Context2Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }" }
                };
                var migrationsBuild = migrationsSource.Build();
                using (var executor = new AppDomainOperationExecutor(targetDir, migrationsBuild.TargetName, targetDir, targetDir, "MyProject"))
                {
                    var contextTypes = executor.GetContextTypes();

                    Assert.Equal(3, contextTypes.Count());
                }
            }
        }
Example #16
0
        public void GetMigrations_filters_by_context_name()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Diagnostics.DiagnosticSource",                                             copyLocal: true),
                        BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                        BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                        BuildReference.ByName("Microsoft.AspNetCore.Hosting.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                                                   copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools.Core",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational.Design",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",                                         copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions",                           copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.FileProviders.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.PlatformAbstractions",                                       copyLocal: true),
                        BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                    },
                    Sources = { @"
                        using Microsoft.EntityFrameworkCore;
                        using Microsoft.EntityFrameworkCore.Infrastructure;
                        using Microsoft.EntityFrameworkCore.Migrations;

                        namespace MyProject
                        {
                            internal class Context1 : DbContext
                            {
                                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                {
                                    optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SimpleProject.SimpleContext;Integrated Security=True"");
                                }
                            }

                            internal class Context2 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [DbContext(typeof(Context1))]
                                    [Migration(""000000000000000_Context1Migration"")]
                                    public class Context1Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [DbContext(typeof(Context2))]
                                    [Migration(""000000000000000_Context2Migration"")]
                                    public class Context2Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }" }
                };
                var build = source.Build();
                using (var executor = new AppDomainOperationExecutor(targetDir, build.TargetName, targetDir, targetDir, "MyProject"))
                {
                    var migrations = executor.GetMigrations("Context1");

                    Assert.Equal(1, migrations.Count());
                }
            }
        }
Example #17
0
        public void GetContextType_works_with_multiple_assemblies()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir      = directory.Path;
                var contextsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("Microsoft.EntityFrameworkCore", true)
                    },
                    Sources = { @"
                        using Microsoft.EntityFrameworkCore;

                        namespace MyProject
                        {
                            public class Context1 : DbContext
                            {
                            }

                            public class Context2 : DbContext
                            {
                            }
                        }" }
                };
                var contextsBuild    = contextsSource.Build();
                var migrationsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Design",                 true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",             true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",             true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions",true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                         true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",            true),
                        BuildReference.ByPath(contextsBuild.TargetPath)
                    },
                    Sources = { @"
                        using Microsoft.EntityFrameworkCore;
                        using Microsoft.EntityFrameworkCore.Infrastructure;
                        using Microsoft.EntityFrameworkCore.Migrations;

                        namespace MyProject
                        {
                            internal class Context3 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [DbContext(typeof(Context1))]
                                    [Migration(""000000000000000_Context1Migration"")]
                                    public class Context1Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [DbContext(typeof(Context2))]
                                    [Migration(""000000000000000_Context2Migration"")]
                                    public class Context2Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }" }
                };
                var build = migrationsSource.Build();
                using (var executor = CreateExecutorFromBuildResult(build, "MyProject"))
                {
                    var contextTypes = executor.GetContextTypes();

                    Assert.Equal(3, contextTypes.Count());
                }
            }
        }
 protected virtual ICollection <BuildReference> GetReferences() => new List <BuildReference>
 {
     BuildReference.ByName("Microsoft.EntityFrameworkCore"),
     BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
     BuildReference.ByName("Pomelo.EntityFrameworkCore.MySql")
 };
        public void Migrations_compile()
        {
            var codeHelper = new CSharpHelper();
            var generator  = new CSharpMigrationGenerator(
                codeHelper,
                new CSharpMigrationOperationGenerator(codeHelper),
                new CSharpModelGenerator(codeHelper));

            var migrationCode = generator.Generate(
                "MyNamespace",
                "MyMigration",
                new MigrationOperation[0],
                new MigrationOperation[0]);

            Assert.Equal(
                @"using System.Collections.Generic;
using Microsoft.Data.Entity.Relational.Migrations;
using Microsoft.Data.Entity.Relational.Migrations.Builders;
using Microsoft.Data.Entity.Relational.Migrations.Operations;

namespace MyNamespace
{
    public partial class MyMigration : Migration
    {
        public override void Up(MigrationBuilder migration)
        {
        }
        
        public override void Down(MigrationBuilder migration)
        {
        }
    }
}
",
                migrationCode);

            var migrationMetadataCode = generator.GenerateMetadata(
                "MyNamespace",
                typeof(MyContext),
                "MyMigration",
                "20150511161616_MyMigration",
                "7.0.0",
                new Model());

            Assert.Equal(
                @"using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Microsoft.Data.Entity.Commands.Migrations;

namespace MyNamespace
{
    [ContextType(typeof(CodeCompilationTest.MyContext))]
    partial class MyMigration
    {
        public override string Id
        {
            get { return ""20150511161616_MyMigration""; }
        }
        
        public override string ProductVersion
        {
            get { return ""7.0.0""; }
        }
        
        public override void BuildTargetModel(ModelBuilder builder)
        {
        }
    }
}
",
                migrationMetadataCode);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName(typeof(CodeCompilationTest).Assembly.GetName().Name),
                    BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                    BuildReference.ByName("EntityFramework.Core"),
                    BuildReference.ByName("EntityFramework.Relational")
                },
                Sources = { migrationCode, migrationMetadataCode }
            };

            var assembly = build.BuildInMemory();

            var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true);

            var contextTypeAttribute = migrationType.GetCustomAttribute <ContextTypeAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            var migration = (Migration)Activator.CreateInstance(migrationType);

            Assert.Equal("20150511161616_MyMigration", migration.Id);
            Assert.Equal("7.0.0", migration.ProductVersion);

            var migrationBuilder = new MigrationBuilder();

            migration.Up(migrationBuilder);
            Assert.Empty(migrationBuilder.Operations);

            migrationBuilder = new MigrationBuilder();
            migration.Down(migrationBuilder);
            Assert.Empty(migrationBuilder.Operations);

            var conventions  = new ConventionSet();
            var modelBuilder = new ModelBuilder(conventions);

            migration.BuildTargetModel(modelBuilder);
            Assert.Empty(modelBuilder.Model.EntityTypes);
        }
        public void GetMigrations_filters_by_context_name()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Diagnostics.DiagnosticSource",                   true),
                        BuildReference.ByName("System.Interactive.Async",                              true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                         true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions",            true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Design",                  true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",              true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",               true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",             true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                   true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",       true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",              true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions", true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                          true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",             true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                          true),
                        BuildReference.ByName("Microsoft.Extensions.Primitives",                       true),
                        BuildReference.ByName("Remotion.Linq",                                         true)
                    },
                    Sources =
                    {
                        @"
                        using Microsoft.EntityFrameworkCore;
                        using Microsoft.EntityFrameworkCore.Infrastructure;
                        using Microsoft.EntityFrameworkCore.Migrations;

                        namespace MyProject
                        {
                            internal class Context1 : DbContext
                            {
                                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                {
                                    optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SimpleProject.SimpleContext;Integrated Security=True"");
                                }
                            }

                            internal class Context2 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [DbContext(typeof(Context1))]
                                    [Migration(""000000000000000_Context1Migration"")]
                                    public class Context1Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [DbContext(typeof(Context2))]
                                    [Migration(""000000000000000_Context2Migration"")]
                                    public class Context2Migration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }"
                    }
                };

                var build = source.Build();
                using (var executor = CreateExecutorFromBuildResult(build, "MyProject", "C#"))
                {
                    var migrations = executor.GetMigrations("Context1");

                    Assert.Single(migrations);
                }
            }
        }
Example #21
0
            public SimpleProject()
            {
                var source = new BuildSource
                {
                    TargetDir  = TargetDir,
                    References =
                    {
                        BuildReference.ByName("System.Collections.Immutable",                          true),
                        BuildReference.ByName("System.Diagnostics.DiagnosticSource",                   true),
                        BuildReference.ByName("System.Interactive.Async",                              true),
                        BuildReference.ByName("System.Data.SqlClient",                                 true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                         true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions",            true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Design",                  true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",              true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",               true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",             true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                   true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",       true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",              true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions", true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                          true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",             true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                          true),
                        BuildReference.ByName("Microsoft.Extensions.Primitives",                       true),
                        BuildReference.ByName("Remotion.Linq",                                         true)
                    },
                    Sources =
                    {
                        @"
                            using Microsoft.EntityFrameworkCore;
                            using Microsoft.EntityFrameworkCore.Infrastructure;
                            using Microsoft.EntityFrameworkCore.Migrations;

                            namespace SimpleProject
                            {
                                internal class SimpleContext : DbContext
                                {
                                    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                    {
                                        optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SimpleProject.SimpleContext;Integrated Security=True"");
                                    }
                                }

                                namespace Migrations
                                {
                                    [DbContext(typeof(SimpleContext))]
                                    [Migration(""20141010222726_InitialCreate"")]
                                    public class InitialCreate : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }"
                    }
                };
                var build = source.Build();

                File.Copy(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, build.TargetPath + ".config");
                Executor = new AppDomainOperationExecutor(
                    build.TargetPath,
                    build.TargetPath,
                    build.TargetDir,
                    build.TargetDir,
                    "SimpleProject",
                    "C#");
            }
Example #22
0
        public void GetMigrations_filters_by_context_name()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Collections.Immutable",                                                    copyLocal: true),
                        BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                        BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                        BuildReference.ByName("EntityFramework.Core",                                                            copyLocal: true),
                        BuildReference.ByName("EntityFramework.Commands",                                                        copyLocal: true),
                        BuildReference.ByName("EntityFramework.Relational",                                                      copyLocal: true),
                        BuildReference.ByName("EntityFramework.Relational.Design",                                               copyLocal: true),
                        BuildReference.ByName("EntityFramework.SqlServer",                                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.CodeAnalysis",                                                          copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Caching.Abstractions",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Caching.Memory",                                              copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.DependencyInjection",                                         copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.DependencyInjection.Abstractions",                            copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Logging",                                                     copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Logging.Abstractions",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.OptionsModel",                                                copyLocal: true),
                        BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                    },
                    Sources = { @"
                        using System;
                        using Microsoft.Data.Entity;
                        using Microsoft.Data.Entity.Metadata;
                        using Microsoft.Data.Entity.Migrations;
                        using Microsoft.Data.Entity.Migrations.Builders;
                        using Microsoft.Data.Entity.Migrations.Infrastructure;

                        namespace MyProject
                        {
                            internal class Context1 : DbContext
                            {
                                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                {
                                    optionsBuilder.UseSqlServer(""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SimpleProject.SimpleContext;Integrated Security=True"");
                                }
                            }

                            internal class Context2 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [ContextType(typeof(Context1))]
                                    public class Context1Migration : Migration
                                    {
                                        public override string Id => ""000000000000000_Context1Migration"";

                                        public override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }

                                        public override void Down(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [ContextType(typeof(Context2))]
                                    public class Context2Migration : Migration
                                    {
                                        public override string Id => ""000000000000000_Context2Migration"";

                                        public override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }

                                        public override void Down(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }" }
                };
                var build = source.Build();
                using (var executor = new ExecutorWrapper(targetDir, build.TargetName + ".dll", targetDir, "MyProject"))
                {
                    var migrations = executor.GetMigrations("Context1");

                    Assert.Equal(1, migrations.Count());
                }
            }
        }
        public void Migrations_compile()
        {
            var codeHelper = new CSharpHelper();
            var generator  = new CSharpMigrationsGenerator(
                codeHelper,
                new CSharpMigrationOperationGenerator(codeHelper),
                new CSharpSnapshotGenerator(codeHelper));

            var migrationCode = generator.GenerateMigration(
                "MyNamespace",
                "MyMigration",
                new MigrationOperation[]
            {
                new SqlOperation
                {
                    Sql = "-- TEST",
                    ["Some:EnumValue"] = RegexOptions.Multiline
                },
                new AlterColumnOperation
                {
                    Name      = "C2",
                    Table     = "T1",
                    ClrType   = typeof(Database),
                    OldColumn = new ColumnOperation
                    {
                        ClrType = typeof(Property)
                    }
                },
                new AddColumnOperation
                {
                    Name    = "C3",
                    Table   = "T1",
                    ClrType = typeof(PropertyEntry)
                }
            },
                new MigrationOperation[0]);

            Assert.Equal(
                @"using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System.Text.RegularExpressions;

namespace MyNamespace
{
    public partial class MyMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(""-- TEST"")
                .Annotation(""Some:EnumValue"", RegexOptions.Multiline);

            migrationBuilder.AlterColumn<Database>(
                name: ""C2"",
                table: ""T1"",
                nullable: false,
                oldClrType: typeof(Property));

            migrationBuilder.AddColumn<PropertyEntry>(
                name: ""C3"",
                table: ""T1"",
                nullable: false);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {

        }
    }
}
",
                migrationCode);

            var migrationMetadataCode = generator.GenerateMetadata(
                "MyNamespace",
                typeof(MyContext),
                "MyMigration",
                "20150511161616_MyMigration",
                new Model {
                ["Some:EnumValue"] = RegexOptions.Multiline
            });

            Assert.Equal(
                @"using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Design.Tests.Migrations.Design;
using System.Text.RegularExpressions;

namespace MyNamespace
{
    [DbContext(typeof(CSharpMigrationsGeneratorTest.MyContext))]
    [Migration(""20150511161616_MyMigration"")]
    partial class MyMigration
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation(""Some:EnumValue"", RegexOptions.Multiline);
        }
    }
}
",
                migrationMetadataCode);

            var build = new BuildSource
            {
                References =
                {
#if NET452
                    BuildReference.ByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                    BuildReference.ByName("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
#else
                    BuildReference.ByName("System.Text.RegularExpressions"),
#endif
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Design.Tests"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational")
                },
                Sources = { migrationCode, migrationMetadataCode }
            };

            var assembly = build.BuildInMemory();

            var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true, ignoreCase: false);

            var contextTypeAttribute = migrationType.GetTypeInfo().GetCustomAttribute <DbContextAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            var migration = (Migration)Activator.CreateInstance(migrationType);

            Assert.Equal("20150511161616_MyMigration", migration.GetId());

            Assert.Equal(3, migration.UpOperations.Count);
            Assert.Empty(migration.DownOperations);
            Assert.Empty(migration.TargetModel.GetEntityTypes());
        }
                public SimpleProject()
                {
                    var source = new BuildSource
                    {
                        TargetDir  = TargetDir,
                        References =
                        {
                            BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                            BuildReference.ByName("EntityFramework.Core",                                                               copyLocal: true),
                            BuildReference.ByName("EntityFramework.Commands",                                                           copyLocal: true),
                            BuildReference.ByName("EntityFramework.Migrations",                                                         copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.Logging",                                                        copyLocal: true),
                            BuildReference.ByName("Microsoft.Framework.Logging.Interfaces",                                             copyLocal: true)
                        },
                        Source = @"
                        using System;
                        using Microsoft.Data.Entity;
                        using Microsoft.Data.Entity.Metadata;
                        using Microsoft.Data.Entity.Migrations;
                        using Microsoft.Data.Entity.Migrations.Builders;
                        using Microsoft.Data.Entity.Migrations.Infrastructure;
                        using Microsoft.Data.Entity.Migrations.Model;

                        namespace SimpleProject
                        {
                            internal class SimpleContext : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                [ContextType(typeof(SimpleContext))]
                                public class InitialCreate : Migration, IMigrationMetadata
                                {
                                    public string MigrationId
                                    {
                                        get { return ""201410102227260_InitialCreate""; }
                                    }

                                    public string ProductVersion
                                    {
                                        get { throw new NotImplementedException(); }
                                    }

                                    public IModel TargetModel
                                    {
                                        get { throw new NotImplementedException(); }
                                    }

                                    public override void Up(MigrationBuilder migrationBuilder)
                                    {
                                    }

                                    public override void Down(MigrationBuilder migrationBuilder)
                                    {
                                    }
                                }
                            }
                        }
                    "
                    };
                    var build = source.Build();

                    _executor = new ExecutorWrapper(TargetDir, build.TargetName + ".dll", TargetDir, "SimpleProject");
                }
        public void GetContextType_works_with_multiple_assemblies()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir      = directory.Path;
                var contextsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                        BuildReference.ByName("EntityFramework.Core",                                                               copyLocal: true),
                        BuildReference.ByName("EntityFramework.Commands",                                                           copyLocal: true)
                    },
                    Source = @"
                        using Microsoft.Data.Entity;

                        namespace MyProject
                        {
                            public class Context1 : DbContext
                            {
                            }

                            public class Context2 : DbContext
                            {
                            }
                        }
                    "
                };
                var contextsBuild    = contextsSource.Build();
                var migrationsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
                        BuildReference.ByName("EntityFramework.Core"),
                        BuildReference.ByName("EntityFramework.Migrations",                                                         copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Logging",                                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Logging.Interfaces",                                             copyLocal: true),
                        BuildReference.ByPath(contextsBuild.TargetPath)
                    },
                    Source = @"
                        using System;
                        using Microsoft.Data.Entity;
                        using Microsoft.Data.Entity.Metadata;
                        using Microsoft.Data.Entity.Migrations;
                        using Microsoft.Data.Entity.Migrations.Builders;
                        using Microsoft.Data.Entity.Migrations.Infrastructure;
                        using Microsoft.Data.Entity.Migrations.Model;

                        namespace MyProject
                        {
                            internal class Context3 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [ContextType(typeof(Context1))]
                                    public class Context1Migration : Migration, IMigrationMetadata
                                    {
                                        public string MigrationId
                                        {
                                            get { return ""000000000000000_Context1Migration""; }
                                        }

                                        public string ProductVersion
                                        {
                                            get { throw new NotImplementedException(); }
                                        }

                                        public IModel TargetModel
                                        {
                                            get { throw new NotImplementedException(); }
                                        }

                                        public override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }

                                        public override void Down(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [ContextType(typeof(Context2))]
                                    public class Context2Migration : Migration, IMigrationMetadata
                                    {
                                        public string MigrationId
                                        {
                                            get { return ""000000000000000_Context2Migration""; }
                                        }

                                        public string ProductVersion
                                        {
                                            get { throw new NotImplementedException(); }
                                        }

                                        public IModel TargetModel
                                        {
                                            get { throw new NotImplementedException(); }
                                        }

                                        public override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
        
                                        public override void Down(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }
                    "
                };
                var migrationsBuild = migrationsSource.Build();
                using (var executor = new ExecutorWrapper(targetDir, migrationsBuild.TargetName + ".dll", targetDir, "MyProject"))
                {
                    var contextTypes = executor.GetContextTypes();

                    Assert.Equal(3, contextTypes.Count());
                }
            }
        }
Example #26
0
        public void GetContextType_works_with_multiple_assemblies()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir      = directory.Path;
                var contextsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("EntityFramework.Core",     copyLocal: true),
                        BuildReference.ByName("EntityFramework.Commands", copyLocal: true)
                    },
                    Sources = { @"
                        using Microsoft.Data.Entity;

                        namespace MyProject
                        {
                            public class Context1 : DbContext
                            {
                            }

                            public class Context2 : DbContext
                            {
                            }
                        }" }
                };
                var contextsBuild    = contextsSource.Build();
                var migrationsSource = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Collections.Immutable",             copyLocal: true),
                        BuildReference.ByName("System.Reflection.Metadata",               copyLocal: true),
                        BuildReference.ByName("EntityFramework.Core"),
                        BuildReference.ByName("EntityFramework.Relational",               copyLocal: true),
                        BuildReference.ByName("EntityFramework.Relational.Design",        copyLocal: true),
                        BuildReference.ByName("Microsoft.CodeAnalysis",                   copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Logging",              copyLocal: true),
                        BuildReference.ByName("Microsoft.Framework.Logging.Abstractions", copyLocal: true),
                        BuildReference.ByPath(contextsBuild.TargetPath)
                    },
                    Sources = { @"
                        using System;
                        using Microsoft.Data.Entity;
                        using Microsoft.Data.Entity.Metadata;
                        using Microsoft.Data.Entity.Migrations;
                        using Microsoft.Data.Entity.Migrations.Builders;
                        using Microsoft.Data.Entity.Migrations.Infrastructure;

                        namespace MyProject
                        {
                            internal class Context3 : DbContext
                            {
                            }

                            namespace Migrations
                            {
                                namespace Context1Migrations
                                {
                                    [ContextType(typeof(Context1))]
                                    public class Context1Migration : Migration
                                    {
                                        public override string Id => ""000000000000000_Context1Migration"";

                                        public override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }

                                        public override void Down(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }

                                namespace Context2Migrations
                                {
                                    [ContextType(typeof(Context2))]
                                    public class Context2Migration : Migration
                                    {
                                        public override string Id => ""000000000000000_Context2Migration"";

                                        public override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }

                                        public override void Down(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }
                        }" }
                };
                var migrationsBuild = migrationsSource.Build();
                using (var executor = new ExecutorWrapper(targetDir, migrationsBuild.TargetName + ".dll", targetDir, "MyProject"))
                {
                    var contextTypes = executor.GetContextTypes();

                    Assert.Equal(3, contextTypes.Count());
                }
            }
        }
Example #27
0
        public void GetMigrations_throws_when_target_and_migrations_assemblies_mismatch()
        {
            using (var directory = new TempDirectory())
            {
                var targetDir = directory.Path;
                var source    = new BuildSource
                {
                    TargetDir  = targetDir,
                    References =
                    {
                        BuildReference.ByName("System.Diagnostics.DiagnosticSource",                                             copyLocal: true),
                        BuildReference.ByName("System.Interactive.Async",                                                        copyLocal: true),
                        BuildReference.ByName("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                        BuildReference.ByName("Microsoft.AspNetCore.Hosting.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore",                                                   copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Tools.Core",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational.Design",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer",                                         copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Caching.Memory",                                             copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Configuration.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection",                                        copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.DependencyInjection.Abstractions",                           copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.FileProviders.Abstractions",                                 copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Logging.Abstractions",                                       copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.Options",                                                    copyLocal: true),
                        BuildReference.ByName("Microsoft.Extensions.PlatformAbstractions",                                       copyLocal: true),
                        BuildReference.ByName("Remotion.Linq",                                                                   copyLocal: true)
                    },
                    Sources = { @"
                            using Microsoft.EntityFrameworkCore;
                            using Microsoft.EntityFrameworkCore.Infrastructure;
                            using Microsoft.EntityFrameworkCore.Migrations;

                            namespace MyProject
                            {
                                internal class MyContext : DbContext
                                {
                                    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                                    {
                                        optionsBuilder
                                            .UseSqlServer(
                                                ""Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MyProject.MyContext;Integrated Security=True"",
                                                b => b.MigrationsAssembly(""UnknownAssembly""));
                                    }
                                }

                                namespace Migrations
                                {
                                    [DbContext(typeof(MyContext))]
                                    [Migration(""20151215152142_MyMigration"")]
                                    public class MyMigration : Migration
                                    {
                                        protected override void Up(MigrationBuilder migrationBuilder)
                                        {
                                        }
                                    }
                                }
                            }" }
                };
                var build = source.Build();
                using (var executor = new AppDomainOperationExecutor(targetDir, build.TargetName, targetDir, targetDir, "MyProject"))
                {
                    var ex = Assert.Throws <OperationException>(
                        () => executor.GetMigrations("MyContext"));

                    Assert.Equal(
                        ToolsCoreStrings.MigrationsAssemblyMismatch(build.TargetName, "UnknownAssembly"),
                        ex.Message);
                }
            }
        }
Example #28
0
        protected void Test(
            Action <ModelBuilder> buildModel,
            ModelCodeGenerationOptions options,
            Action <ScaffoldedModel> assertScaffold,
            Action <IModel> assertModel,
            bool skipBuild = false)
        {
            var designServices = new ServiceCollection();

            AddModelServices(designServices);

            var modelBuilder = SqlServerTestHelpers.Instance.CreateConventionBuilder(customServices: designServices);

            modelBuilder.Model.RemoveAnnotation(CoreAnnotationNames.ProductVersion);
            buildModel(modelBuilder);

            var model = modelBuilder.FinalizeModel(designTime: true, skipValidation: true);

            var services = CreateServices();

            AddScaffoldingServices(services);

            var generator = services.BuildServiceProvider(validateScopes: true)
                            .GetRequiredService <IModelCodeGenerator>();

            options.ModelNamespace ??= "TestNamespace";
            options.ContextName      = "TestDbContext";
            options.ConnectionString = "Initial Catalog=TestDatabase";

            var scaffoldedModel = generator.GenerateModel(
                model,
                options);

            assertScaffold(scaffoldedModel);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Abstractions"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.Relational"),
                    BuildReference.ByName("Microsoft.EntityFrameworkCore.SqlServer")
                },
                Sources = new[] { scaffoldedModel.ContextFile }.Concat(scaffoldedModel.AdditionalFiles)
                .ToDictionary(f => f.Path, f => f.Code),
                NullableReferenceTypes = options.UseNullableReferenceTypes
            };

            if (!skipBuild)
            {
                var assembly = build.BuildInMemory();

                if (assertModel != null)
                {
                    var contextNamespace = options.ContextNamespace ?? options.ModelNamespace;
                    var context          = (DbContext)assembly.CreateInstance(
                        !string.IsNullOrEmpty(contextNamespace)
                            ? contextNamespace + "." + options.ContextName
                            : options.ContextName);

                    var compiledModel = context.GetService <IDesignTimeModel>().Model;
                    assertModel(compiledModel);
                }
            }
        }
Example #29
0
        public void Snapshots_compile()
        {
            var codeHelper = new CSharpHelper();
            var generator  = new CSharpMigrationsGenerator(
                codeHelper,
                new CSharpMigrationOperationGenerator(codeHelper),
                new CSharpSnapshotGenerator(codeHelper));

            var modelSnapshotCode = generator.GenerateSnapshot(
                "MyNamespace",
                typeof(MyContext),
                "MySnapshot",
                new Model {
                ["Some:EnumValue"] = RegexOptions.Multiline
            });

            Assert.Equal(@"using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.Commands.Migrations;
using System.Text.RegularExpressions;

namespace MyNamespace
{
    [DbContext(typeof(CodeCompilationTest.MyContext))]
    partial class MySnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation(""Some:EnumValue"", RegexOptions.Multiline);
        }
    }
}
", modelSnapshotCode);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName(typeof(CodeCompilationTest).GetTypeInfo().Assembly.GetName().Name),
#if DNXCORE50
                    BuildReference.ByName("System.Text.RegularExpressions"),
#else
                    BuildReference.ByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                    BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
#endif
                    BuildReference.ByName("EntityFramework.Core"),
                    BuildReference.ByName("EntityFramework.Relational")
                },
                Sources = { modelSnapshotCode }
            };

            var assembly = build.BuildInMemory();

            var snapshotType = assembly.GetType("MyNamespace.MySnapshot", throwOnError: true, ignoreCase: false);

            var contextTypeAttribute = snapshotType.GetTypeInfo().GetCustomAttribute <DbContextAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            var snapshot = (ModelSnapshot)Activator.CreateInstance(snapshotType);

            Assert.Empty(snapshot.Model.GetEntityTypes());
        }
Example #30
0
        public void Migrations_compile()
        {
            var codeHelper = new CSharpHelper();
            var generator  = new CSharpMigrationsGenerator(
                codeHelper,
                new CSharpMigrationOperationGenerator(codeHelper),
                new CSharpSnapshotGenerator(codeHelper));

            var migrationCode = generator.GenerateMigration(
                "MyNamespace",
                "MyMigration",
                new[] {
                new SqlOperation
                {
                    Sql = "-- TEST",
                    ["Some:EnumValue"] = RegexOptions.Multiline
                }
            },
                new MigrationOperation[0]);

            Assert.Equal(
                @"using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
using System.Text.RegularExpressions;

namespace MyNamespace
{
    public partial class MyMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(""-- TEST"")
                .Annotation(""Some:EnumValue"", RegexOptions.Multiline);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {

        }
    }
}
",
                migrationCode);

            var migrationMetadataCode = generator.GenerateMetadata(
                "MyNamespace",
                typeof(MyContext),
                "MyMigration",
                "20150511161616_MyMigration",
                new Model {
                ["Some:EnumValue"] = RegexOptions.Multiline
            });

            Assert.Equal(
                @"using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using Microsoft.Data.Entity.Commands.Migrations;
using System.Text.RegularExpressions;

namespace MyNamespace
{
    [DbContext(typeof(CodeCompilationTest.MyContext))]
    [Migration(""20150511161616_MyMigration"")]
    partial class MyMigration
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation(""Some:EnumValue"", RegexOptions.Multiline);
        }
    }
}
",
                migrationMetadataCode);

            var build = new BuildSource
            {
                References =
                {
                    BuildReference.ByName(typeof(CodeCompilationTest).GetTypeInfo().Assembly.GetName().Name),
#if DNXCORE50
                    BuildReference.ByName("System.Text.RegularExpressions"),
#else
                    BuildReference.ByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"),
                    BuildReference.ByName("System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
#endif
                    BuildReference.ByName("EntityFramework.Core"),
                    BuildReference.ByName("EntityFramework.Relational")
                },
                Sources = { migrationCode, migrationMetadataCode }
            };

            var assembly = build.BuildInMemory();

            var migrationType = assembly.GetType("MyNamespace.MyMigration", throwOnError: true, ignoreCase: false);

            var contextTypeAttribute = migrationType.GetTypeInfo().GetCustomAttribute <DbContextAttribute>();

            Assert.NotNull(contextTypeAttribute);
            Assert.Equal(typeof(MyContext), contextTypeAttribute.ContextType);

            var migration = (Migration)Activator.CreateInstance(migrationType);

            Assert.Equal("20150511161616_MyMigration", migration.GetId());

            Assert.Equal(1, migration.UpOperations.Count);
            Assert.Empty(migration.DownOperations);
            Assert.Empty(migration.TargetModel.GetEntityTypes());
        }