获取脚本来创建数据库,包括初始化数据

时间:2013-04-19 13:16:38

标签: entity-framework ef-code-first entity-framework-5 ef-migrations

我想知道Entity Framework的迁移是否有可能让sql脚本创建我的数据库的内容,包括Configuration类中seed方法的所有数据:

protected override void Seed(Sotasa.DAL.SqlContext context)
{
    //Data I'd like to be included to the script
}

Update-Database命令的帮助看起来不像是这样:

Update-Database [-SourceMigration <String>] [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName 
<String>] [-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String> [<CommonParameters>]

2 个答案:

答案 0 :(得分:0)

这是不可能的。 (要在Seed方法中生成数据,生成SQL语句)。

另一种解决方法是使用脚本来构建 - &gt;创建数据库 - &gt;用数据编写数据库脚本? (Powershell可能会利用sql server管理对象。)

答案 1 :(得分:0)

这就是我所做的,可能不是那么漂亮,但它适用于我们(注意这是我们当地的开发和CI环境):

public class Configuration : DbMigrationsConfiguration<MyContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        SetSqlGenerator(OracleConnectionInfo.InvariantName, new OracleEntityMigrationSqlGenerator());
    }

    protected override void Seed(MyContext context)
    {
        Logger.Write("In Seed method. User: " + userName);
        MyInitializer.AddUpdateDataSql(context);
    }
}

public class MyInitializer : MigrateDatabaseToLatestVersion<MyContext, Configuration>
{
    private const string Schemaname = "MYSCHEMA";

    public static void AddUpdateDataSql(Pronova2Context context)
    {
        DeleteTableData(context);
        DropCreateSequences(context);
        PopulateTypeTypeData(context);
        // etc.
    }

    private static void DeleteTableData(DbContext context)
    {
        context.Database.ExecuteSqlCommand(@"delete " + Schemaname + ".T_TABLE1"); }
        context.Database.ExecuteSqlCommand(@"delete " + Schemaname + ". T_TABLE2"); }
        // etc.
    }

    private static void DropCreateSequences(DbContext context)
    {
        context.Database.ExecuteSqlCommand(@"DROP SEQUENCE  " + Schemaname + ".T_TABLE1_SEQ"); }
        context.Database.ExecuteSqlCommand(@"DROP SEQUENCE  " + Schemaname + ".T_TABLE2_SEQ"); }
        // etc.
    }

    private static void PopulateTypeTypeData(DbContext context)
    {
        try { context.Database.ExecuteSqlCommand(@"Insert into " + Schemaname + ".T_TYPE_TYPE (TYPE_TYPE_ID,NAME,DESCRIPTION) values (1,'TypeType1','Name 1')");
        try { context.Database.ExecuteSqlCommand(@"Insert into " + Schemaname + ".T_TYPE_TYPE (TYPE_TYPE_ID,NAME,DESCRIPTION) values (2,'TypeType1','Name 2')");
        // etc.
    }
}