【问题标题】:How to setup EF6 Migrations with ASP.NET Core如何使用 ASP.NET Core 设置 EF6 迁移
【发布时间】:2017-06-30 05:34:50
【问题描述】:

我正在尝试采用 Jimmy Bogard 的 ContosoUniversityCore project

我想先进行代码迁移,但不确定如何正确设置。 我将 Migrator.EF6.Tools 添加到我的项目中。

当我运行 Enable-Migrations 我收到此错误:

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not 
marked as serializable."
At C:\Users\SomeUser\.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:718 char:5
+     $domain.SetData('project', $project)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not 
marked as serializable."
At C:\Users\SomeUser\.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:719 char:5
+     $domain.SetData('contextProject', $contextProject)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SerializationException

Exception calling "SetData" with "2" argument(s): "Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject' in assembly 'Microsoft.VisualStudio.ProjectSystem.VS.Implementation, Version=14.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' is not 
marked as serializable."
At C:\Users\SomeUser\.nuget\packages\entityframework\6.1.3\tools\EntityFramework.psm1:720 char:5
+     $domain.SetData('startUpProject', $startUpProject)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SerializationException

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetPropertyValue[T](Project project, String propertyName)
   at System.Data.Entity.Migrations.MigrationsDomainCommand.GetFacade(String configurationTypeName, Boolean useContextWorkingDirectory)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.

【问题讨论】:

    标签: asp.net-core entity-framework-6 entity-framework-migrations


    【解决方案1】:

    这里真正的问题是存在不同的 EF“口味”。只需转到 EF 根文档并查看差异:

    这是我在 EF 6 和 .NET Core 中使用迁移的秘诀:

    1st.- 您必须将这些行添加到 .csproj

    <ItemGroup>
        <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.1" />
        <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.1" />
    </ItemGroup>
    

    注意:版本已更改

    2nd.- 在您的项目中创建上下文,如下所示:

    public class YourContext : DbContext
    {
        #region Constructors
    
        public YourContext()
        {
        }
    
        public YourContext(DbContextOptions options) : base(options)
        {
    
        }
    
        #region DbSets  // YOUR DB SETS GO HERE...
        #endregion DbSets
    
        #region OnConfiguring // THIS HELPED ME A LOT:
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // In order to be able to create migrations and update database:
            if (!options.IsConfigured)
            {
                options.UseSqlServer("YourLocalConnectionStringShouldBeHere");
            }
            base.OnConfiguring(options);
        }
        #endregion
    
        #region Model Creating
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           // Your Model Crerating Stuff
        }
    
        #endregion Model Creating
    }
    

    3rd.- 添加迁移

    转到项目文件夹,从 cmd 键入:

    dotnet ef migrations add [NameOFYourMigrationGoesHere] -c YourContext
    

    注意:不要忘记将创建的文件添加到源代码管理,这不是自动完成的

    4rd.- 更新你的数据库: 4.a.- 在 docker 中 -> 您可以运行项目(完全使用 Docker),迁移将在第一次使用 Context 时应用。

    注意:(它将使用为该环境配置的连接字符串)

    4.b.- 您的本地数据库 -> 编辑在 ConfigurationContext.OnConfigure 中硬编码的连接字符串并运行(从 cmd 控制台):

    dotnet ef database update --context ConfigurationContext
    

    希望对你有帮助。

    胡安

    【讨论】:

    • Microsoft.EntityFrameworkCore.Tools.DotNetOnConfiguring 仅是 EF7 功能。您没有为 EF6.1.3 提供解决方案。
    【解决方案2】:

    您的 EF6 项目必须提供 IDbContextFactory 的实现。 EF6 命令行工具将找到并使用该实现,以便它们可以实例化上下文。这是一个例子。

        public class SchoolContextFactory : IDbContextFactory<SchoolContext>
         {
        public SchoolContext Create()
        {
            return new EF6.SchoolContext("Server=(localdb)\\mssqllocaldb;          Database=EF6MVCCore;Trusted_Connection=True;MultipleActiveResultSets=true");
        }
       }
    

    在核心项目的 Startup.cs 文件中,为 ConfigureServices 中的依赖注入 (DI) 设置 EF6 上下文。 EF 上下文对象的范围应为每个请求的生命周期。

     public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddScoped<SchoolContext>(_ => new SchoolContext(Configuration.GetConnectionString("DefaultConnection")));
    }
    

    在两个项目的包管理器控制台 (PMC) 中,运行命令 Install-Package Entityframework。

    在类库项目中,创建数据模型类和上下文类,以及 IDbContextFactory 的实现。

    在类库项目的 PMC 中,运行命令 Enable-Migrations 和 Add-Migration Initial。如果您已将 ASP.NET Core 项目设置为启动项目,请将 -StartupProjectName EF6 添加到这些命令中。 在 Startup.cs 中,在 appsettings.json 中注册 DI 的上下文,添加连接字符串。

    欲了解更多信息,请访问

    https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6

    【讨论】:

      【解决方案3】:

      问题是 EF 6 迁移不习惯使用新的 csproj 格式。

      帮助我的是this 项目。

      查看其主页上的说明。

      通常,您只需按照说明的方式将包添加到您的项目中,然后迁移就可以工作了。

      【讨论】:

        猜你喜欢
        • 2019-03-20
        • 2018-08-15
        • 1970-01-01
        • 2023-03-18
        • 2015-12-11
        • 2013-05-26
        • 2016-11-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多