C# 从控制台应用程序运行迁移时,我缺少哪些文件?

C# 从控制台应用程序运行迁移时,我缺少哪些文件?,c#,entity-framework,mono,entity-framework-migrations,resx,C#,Entity Framework,Mono,Entity Framework Migrations,Resx,有了Entity Framework 6和一个正常工作的PostgreSQL数据库plus连接,我尝试运行添加迁移和更新数据库命令,并通过控制台应用程序创建更新脚本。可以从控制台运行命令,因为它“只是API的薄包装”,请参阅我使用的示例 创建迁移工作时,将创建三个常规文件,即: Initial.csInitial.Designer.csInitial.resx 这里的控制台应用程序不适用于更新数据库 public static void Main() { // Specify the

有了Entity Framework 6和一个正常工作的PostgreSQL数据库plus连接,我尝试运行
添加迁移
更新数据库
命令,并通过控制台应用程序创建更新脚本。可以从控制台运行命令,因为它“只是API的薄包装”,请参阅我使用的示例

创建迁移工作时,将创建三个常规文件,即:

Initial.cs
Initial.Designer.cs
Initial.resx

这里的控制台应用程序不适用于
更新数据库

public static void Main()
{

    // Specify the name of the database migration
    // Note: make sure to create a new name for each new migration and prefix with
    const string MIGRATION_NAME = "Initial";

    // END USER INPUT


    // Get executing path from which the location of the Update_Scripts and new 
    // Migrations can be determined.
    var executingPath = AppDomain.CurrentDomain.BaseDirectory; 



    // Write to database (PowerShell: Update-Database)
    var config = new Configuration();
    var migrator = new DbMigrator(config);
    migrator.Update(); // <= HERE IT CRASHES!

    // Now create the PostgreSQL update script.
    var scriptor = new MigratorScriptingDecorator (migrator);
    string script = scriptor.ScriptUpdate (sourceMigration: null, targetMigration: null);

    var updateScriptPath = Regex.Replace (executingPath, "Zk.Migrations/.*", 
                        "Zk/App_Data/Update_Scripts");
    File.WriteAllText (updateScriptPath + MIGRATION_NAME + ".postgresql", script);
    Console.WriteLine ("Update script {0} written to App_Data/Update_Scripts folder", MIGRATION_NAME);
}
其中
PostgreSqlMigrationSqlGenerator
类来自

当我试图运行控制台上的更新数据库部分时,应用程序在
migrator.Update()上崩溃。这是一个例外:

找不到任何适合指定区域性或非特定区域性的资源。确保在编译时将“Zk.Migrations.Initial.resources”正确嵌入或链接到程序集“Zk.Migrations”,或者确保所需的所有附属程序集都是可加载和完全签名的

这是堆栈跟踪:

System.Data.Entity.Migrations.Dbmigator.EnsureDatabaseExists(mustSucceedToKeepDatabase=
{System.Action})在中 System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists
(mustSucceedToKeepDatabase={System.Action})位于


Zk.Migrations.migrationtool.Main()位于/home/erwin/zaaikalender/Zk.Migrations
/migrationtool.cs:78


我不知道如何提供正确的资源并使脚本正常工作。我是否应该首先运行
启用迁移
,如果是,如何运行?我希望有人能帮助我!谢谢。

要让console应用程序运行,需要做两件事来添加代码优先迁移、创建脚本和更新数据库:

  • 为添加迁移时创建的
    .cs.
    .resx
    .Designer.cs
    文件提供与迁移支架名称相同的名称,而不提供迁移的
    MigrationId
    。否则无法找到文件
  • 右键单击resources
    .resx
    文件并选择BuildAction“EmbeddedResource”,否则无法找到资源
  • 控制台应用程序的完整工作脚本(使用):

    //
    ///类,用于根据模型生成代码迁移和SQL脚本并更新数据库。
    ///(即,运行PowerShell的添加迁移和更新数据库,并创建PostgreSQL脚本。)
    ///见:http://stackoverflow.com/questions/20374783/enable-entity-framework-migrations-in-mono#20382226
    /// 
    ///用法:通过将Zk.Migrations设置为启动项目并按play来运行。
    /// 
    ///命名空间EntityFramework.PostgreSql的类来自:
    ///     https://github.com/darionato/PostgreSqlMigrationSqlGenerator. 包括许可证。
    /// 
    类迁移工具
    {
    /// 
    ///程序的入口点,程序控制从这里开始和结束。
    /// 
    公共静态void Main()
    {
    //用户输入/////////////////////////////////////////////////////////////////////////////////
    //始终首先使用DatabaseStep.ADD\u migration创建新的数据库迁移,
    //并将创建的文件包括在项目中,并将资源文件设置为EmbeddedResource。
    //创建迁移后,运行UPDATE_DATABASE以更新数据库。
    const DatabaseStep=DatabaseStep.UPDATE_数据库;
    //如果是添加迁移,请指定数据库迁移的名称。
    //注意:确保为每个新迁移创建一个新名称。
    //创建迁移后,通过右键单击将文件包括在文件夹中
    //Zk.Migrations并选择“从文件夹添加文件”。然后添加.cs、.resx和
    //.Designer.cs文件,其名称如下所示。
    //最后但并非最不重要的一点是将.resx文件的构建操作设置为EmbeddedResource
    //点击它。
    //确保Setup.postgresql脚本已手动运行以创建数据库用户。
    常量字符串迁移\u NAME=“CalendarAndUser”;
    //最终用户输入/////////////////////////////////////////////////////////////////////////////
    //获取执行路径,从中可以确定更新_脚本和新迁移的位置。
    var executingPath=AppDomain.CurrentDomain.BaseDirectory;
    //添加新迁移(PowerShell:添加迁移)
    if(step==DatabaseStep.ADD\u迁移){
    //围绕实体框架PowerShell API初始化包装器类。
    var config=新配置();
    var scaffolder=new MigrationScaffolder(配置);
    var migration=scaffolder.Scaffold(迁移名称);
    //将迁移代码放在主项目“Migrations”文件夹中,将迁移脚本放在“App_Data”中
    var migrationpath=Regex.Replace(executingPath,“bin/*”,“”);
    //写迁移
    File.writealText(migrationPath+MIGRATION_NAME+“.cs”,MIGRATION.UserCode);
    File.writealText(migrationPath+MIGRATION_NAME+“.Designer.cs”,MIGRATION.DesignerCode);
    使用(var writer=new resxresourceswriter(migrationsPath+MIGRATION_NAME+“.resx”))
    {
    foreach(migration.Resources中的var资源)
    {
    writer.AddResource(resource.Key、resource.Value);
    }
    }
    Console.WriteLine(“EF代码迁移{0}写入迁移文件夹…\n\n”+
    “下一步是在项目中包括.cs、.resx和.Designer.cs文件”
    
    public class Configuration : DbMigrationsConfiguration<ZkContext>
    {
        public Configuration ()
        {
            AutomaticMigrationsEnabled = false;
            SetSqlGenerator("Npgsql", new PostgreSqlMigrationSqlGenerator());
        }
    
    }
    
    /// <summary>
    ///     Class used to generate the code migrations and SQL script based on the Models and update the database.
    ///     (I.e., runs PowerShell's Add-Migration and Update-Database, and creates a PostgreSQL script.)
    ///     See: http://stackoverflow.com/questions/20374783/enable-entity-framework-migrations-in-mono#20382226
    /// 
    ///     Usage: run by setting Zk.Migrations as Startup project and pressing play.
    /// 
    ///     Classes of namespace EntityFramework.PostgreSql obtained from:
    ///     https://github.com/darionato/PostgreSqlMigrationSqlGenerator. License is included.
    /// </summary>
    class MigrationsTool
    {
        /// <summary>
        ///     The entry point of the program, where the program control starts and ends.
        /// </summary>
        public static void Main()
        {
            // USER INPUT /////////////////////////////////////////////////////////////////////////////////
    
            // Always first create a new database migration with DatabaseStep.ADD_MIGRATION,
            // and include the created files in the project and set resource file to EmbeddedResource. 
            // After creating a migration run UPDATE_DATABASE to update the database.
    
            const DatabaseStep step = DatabaseStep.UPDATE_DATABASE;
    
            // Specify the name of the database migration in case of ADD-MIGRATION.
            // Note: Make sure to create a new name for each new migration.
            //       After creating migration include the files in the folder by right clicking on 
            //       Zk.Migrations and selecting "Add files from folder". Then add the .cs, .resx and
            //       .Designer.cs files with the name specified below.
            //       Last but not least set the .resx file's build action to EmbeddedResource by right
            //       clicking on it.
            // Make sure that the Setup.postgresql script has run manually to create the database user.
    
            const string MIGRATION_NAME = "CalendarAndUser";
    
            // END USER INPUT /////////////////////////////////////////////////////////////////////////////
    
    
            // Get executing path from which the location of the Update_Scripts and new Migrations can be determined.
            var executingPath = AppDomain.CurrentDomain.BaseDirectory; 
    
            // Add a new migration (PowerShell: Add-Migration)
            if (step == DatabaseStep.ADD_MIGRATION) {
    
                // Initialize the wrapper classes around the Entity Framework PowerShell API.
                var config = new Configuration();
                var scaffolder = new MigrationScaffolder(config); 
                var migration = scaffolder.Scaffold(MIGRATION_NAME);
    
                // Place migration code in main project "Migrations" folder and migration scripts in "App_Data"
                var migrationsPath = Regex.Replace(executingPath, "bin/.*", "");
    
                // Write migrations
                File.WriteAllText (migrationsPath + MIGRATION_NAME + ".cs", migration.UserCode);
                File.WriteAllText (migrationsPath + MIGRATION_NAME + ".Designer.cs", migration.DesignerCode);
    
                using (var writer = new ResXResourceWriter (migrationsPath + MIGRATION_NAME + ".resx")) 
                {
                    foreach (var resource in migration.Resources) 
                    {
                        writer.AddResource(resource.Key, resource.Value);
                    }
                }
                Console.WriteLine("EF code migration {0} written to Migrations folder...\n\n" +
                    "Next step is to include the .cs, .resx and .Designer.cs file in the project" + 
                    "by right clicking on the project and selecting " +  
                    "\"Add files from folder.\"\n" +
                    "Then right click on {0}.resx and set build action to \"EmbeddedResource\""
                    , migration.MigrationId);
            }
    
            else if (step == DatabaseStep.CREATE_SCRIPT)
            {
                var config = new Configuration();
                var migrator = new DbMigrator(config);
                var scriptor = new MigratorScriptingDecorator(migrator);
    
                // Determine name of the previous run migration if exists.
                string lastMigration = migrator.GetDatabaseMigrations().LastOrDefault();
    
                // Get the script 
                string script = scriptor.ScriptUpdate(sourceMigration: lastMigration, targetMigration: MIGRATION_NAME);
    
                // Create the PostgreSQL update script based on last migration on database and 
                // current migration.
                string formattedScript = string.Format
                    ("/* * * * * * * * * * * * * * * * * * * * * * *\n" +
                    " *\n" +
                    " * Migration:\t\t{0}\n *\n" +
                    " * Date and time:\t{1}\n" +
                    " *\n" +
                    " * * * * * * * * * * * * * * * * * * * * * * */\n\n" +
                    "{2}", 
                    MIGRATION_NAME, 
                    DateTime.Now,
                    script);
    
                // Write string to file in Migrations folder of main project
                var updateScriptPath = Regex.Replace(executingPath, "Zk.Migrations/.*", "Zk/App_Data/Migrations/");
                File.WriteAllText(updateScriptPath + MIGRATION_NAME + ".postgresql", formattedScript);
                Console.WriteLine("Update script {0}.postgresql written to Zk/App_Data/Migrations folder.\n" +
                    "Please include the script by right clicking on the folder and selecting " + 
                    "\"Add files to folder\"," +
                    "\nIt is recommended to prefix the filename with the current datetime.", 
                    MIGRATION_NAME);
            }
    
            // If a new migration is created the database can be updated. (PowerShell: Update-Database)
            else if (step == DatabaseStep.UPDATE_DATABASE)
            {
                var config = new Configuration();
                var migrator = new DbMigrator(config);
    
                // Write to database
                migrator.Update();
    
                // Show which migrations were applied.
                var migrationNames = string.Join(", ", migrator.GetDatabaseMigrations().ToArray().First());
                Console.WriteLine("Applied migration {0} to database.", migrationNames);
            }
        }
    
        /// <summary>
        ///     Enumeration for specifying the step in the migration.
        /// </summary>
        private enum DatabaseStep 
        {
            ADD_MIGRATION,
            CREATE_SCRIPT,
            UPDATE_DATABASE
        }
    
    }