是否可以更改EF Migrations"Migrations"文件夹的位置?

shr*_*rds 41 entity-framework-4 ef-migrations

默认情况下,add-migration命令尝试在其中创建迁移.cs文件

  • 项目根
    • 迁移

我想将我的迁移以及其余的EF相关代码存储在我项目的\ Data文件夹中:

  • 项目根
    • 数据
      • 迁移

有了这个结构,当我执行时

PM> add-migration Migration1
Run Code Online (Sandbox Code Playgroud)

在NuGet控制台中,我收到以下错误:

    System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\MyProjectRoot\Migrations\201112171635110_Migration1.cs'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
   at System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding)
   at System.IO.File.WriteAllText(String path, String contents)

是否可以在执行add-migration命令时指定磁盘上应创建迁移文件的位置?

Rog*_*ger 62

在配置类构造函数中添加以下行:

this.MigrationsDirectory = "DirOne\\DirTwo";
Run Code Online (Sandbox Code Playgroud)

命名空间将继续设置为配置类本身的命名空间.要更改此行,请添加此行(也在配置构造函数中):

this.MigrationsNamespace = "MyApp.DirOne.DirTwo";
Run Code Online (Sandbox Code Playgroud)

  • 这个配置类在哪里? (4认同)
  • +1给我带来了很多麻烦.我浏览了所有的Pluralsight视频,试图找到一个不继承迁移文件夹位置的默认配置的示例.你是一个救星. (2认同)

Mar*_*tin 18

在调用enable-migrations命令(创建Configuration类)期间,也可以使用以下-MigrationsDirectory参数指定迁移文件夹:

enable-migrations -EnableAutomaticMigration:$false -MigrationsDirectory Migrations\CustomerDatabases -ContextTypeName FullyQualifiedContextName
Run Code Online (Sandbox Code Playgroud)

该示例将创建一个Configuration类,该类MigrationsDirectory将指定文件夹"Migrations\CustomerDatabases"设置为相对于项目根文件夹.

public Configuration()
{
    AutomaticMigrationsEnabled = false;
    MigrationsDirectory = @"Migrations\CustomerDatabases";
}
Run Code Online (Sandbox Code Playgroud)


另请参见文章这也解释了关于与多个上下文和迁移文件夹的项目.

顺便说一句,如果您使用多个迁移文件夹和多个上下文,请考虑在派生类的OnModelCreating方法中设置默认模式的名称DbContext(Fluent-API配置的位置).这将适用于EF6:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("CustomerDatabases");
    }
Run Code Online (Sandbox Code Playgroud)

将使用模式名称为数据库表添加前缀.这使您可以在具有多组独立于另一个表的方案中使用多个上下文与单个数据库.(这也将创建MigrationHistory表的单独版本,在上面的示例中它将是CustomerDatabases.__MigrationHistory).