如何使用 ASP.NET Core 设置 EF6 迁移

人气:560 发布:2022-10-16 标签: entity-framework-6 asp.net-core entity-framework-migrations

问题描述

我正在尝试采用 Jimmy Bogard 的 ContosoUniversityCore 项目

I am trying to adopt Jimmy Bogard's ContosoUniversityCore project

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

I would like to do code first migrations, but not sure how to properly set it up. I added Migrator.EF6.Tools to my project.

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

When I run Enable-Migrations I get this error:

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:UsersSomeUser.nugetpackagesentityframework6.1.3	oolsEntityFramework.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:UsersSomeUser.nugetpackagesentityframework6.1.3	oolsEntityFramework.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:UsersSomeUser.nugetpackagesentityframework6.1.3	oolsEntityFramework.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.

推荐答案

这里真正的问题是存在不同的 EF风味".只需转到 EF 根文档并查看差异:

The real issue here is that there are different EF "flavours". Just go to EF root documentation and see the differences:

EF(根文档文件夹):https://docs.microsoft.com/en-us/ef/ EF 6 迁移命令:https://dzone.com/articles/ef-migrations-命令 EF Core 迁移命令:https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations 迁移命令在 .Net Core 中发生了很大变化,我推荐另请访问:https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet EF (root documentation folder): https://docs.microsoft.com/en-us/ef/ EF 6 migrations commands: https://dzone.com/articles/ef-migrations-command EF Core migrations commands: https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations Migration Commands has changed a lot in .Net Core I recommend to visit also: https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet

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

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

1st.- You must add these lines to the .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 键入:

Go to the project folder and, from cmd, type:

dotnet ef migrations add [NameOFYourMigrationGoesHere] -c YourContext

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

NOTE: Don't forget to add created files to source control, that's not done auto-magically

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

4rd.- UPDATE YOUR DB's: 4.a.- In docker -> You can run the project (entirely with Docker) and the migration would be applied at the first Context usage.

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

note: (It will use the configured connection string for that environment)

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

4.b.- Your Local DB -> Edit the Connection String hardcoded in ConfigurationContext.OnConfigure and run (from cmd console):

dotnet ef database update --context ConfigurationContext

希望对你有帮助.

胡安

477