如何使用代码设置默认值首先迁移C#for Database

时间:2013-04-20 14:31:02

标签: c#-4.0 asp.net-mvc-4 ef-code-first ef-migrations

我的问题非常简单......在使用该工具从头开始生成新数据库时,是否可以使用代码优先迁移和C#将默认值设置为国家/地区或标记或状态?如果是的话,你能解释我有多喜欢吗?

2 个答案:

答案 0 :(得分:0)

是的,您可以在迁移中运行原始SQL以插入数据:

public partial class InitialCreate : DbMigration
{
    public override void Up()
    {
        this.Sql("INSERT ...");
    }
    ...
}

或者,您可以在上次迁移运行后访问您的上下文,并可以在那里插入数据:

public sealed class MyConfiguration : DbMigrationsConfiguration<MyContext>
{
   public MyConfiguration()
   {
       this.AutomaticMigrationsEnabled = false;
   }

   protected override void Seed(MyContext context)
   {
       context.Users.AddOrUpdate(u => u.Id, this.GetMyUsers());
       ...
   }
}

答案 1 :(得分:0)

您还可以在Seed方法中使用原始sql来执行此操作。 AddOrUpdate不能用于我的场景,所以我最终这样做了:

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.
    }
}