2011-12-17 73 views
34

默认情况下,附加迁移命令尝试在是否可以更改EF Migrations“Migrations”文件夹的位置?

  • 项目以创建迁移cs文件根
    • 迁移

我想沿着存储我的迁移与我的项目的\ Data文件夹中其余的EF相关的代码:

  • 项目根
    • 数据
      • 迁移

采用这种结构,当我在的NuGet控制台收到以下错误执行

PM> add-migration Migration1 

 
    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命令时应创建迁移文件的位置?

+0

请标记罗杰的解决方案作为答案。它为我工作。谢谢。 – jordanbtucker 2012-09-04 17:09:22

回答

55

在配置类的构造函数中加入这一行:

this.MigrationsDirectory = "DirOne\\DirTwo"; 

的命名空间将继续被设置为配置类本身的命名空间。为了改变这种添加本线(也在配置构造函数):

this.MigrationsNamespace = "MyApp.DirOne.DirTwo"; 
+2

+1救了我一吨麻烦。我浏览了我的所有Pluralsight视频,试图找到一个不会继承此迁移文件夹位置的默认配置的示例。你是救生员。 – JustinMichaels 2012-11-08 17:28:41

+0

有没有什么方法在'web.config'文件中指定这个? – 2015-09-21 09:04:48

+0

这个配置类在哪里? – 2017-01-12 05:52:19

10

指定迁移文件夹中的enable-migrations命令(其创建Configuration类)的调用期间也是可能的,使用所述-MigrationsDirectory参数:

enable-migrations -EnableAutomaticMigration:$false -MigrationsDirectory Migrations\CustomerDatabases -ContextTypeName FullyQualifiedContextName 

该示例将创建一个Configuration类,该类将MigrationsDirectory设置为与项目根文件夹相关的指定文件夹'Migrations \ CustomerDatabases'。

public Configuration() 
{ 
    AutomaticMigrationsEnabled = false; 
    MigrationsDirectory = @"Migrations\CustomerDatabases"; 
} 


又见this文章这也解释了关于与多个上下文和迁移文件夹的项目。顺便说一下,如果您正在使用多个迁移文件夹和多个上下文,请考虑在方法DbContext派生类(其中Fluent-API配置为)的OnModelCreating方法中为默认架构设置一个名称。 这将在EF6工作:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.HasDefaultSchema("CustomerDatabases"); 
    } 

的前缀将您的架构名称数据库表。这将使您能够在具有多组独立于另一组的表的情况下使用单个数据库的多个上下文。 (这也将创建MigrationHistory表的单独版本,在上面的示例中它将是CustomerDatabases.__MigrationHistory)。