EF 5 Code First DbMigration自动化 [英] EF 5 Code First DbMigration automation

查看:59
本文介绍了EF 5 Code First DbMigration自动化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码优先方法中使用EF 5。

I'm using EF 5 with the Code First Approach.

我在设置默认的 DateTime 将列的值设置为(getdateutc())

I'm having trouble setting the default DateTime value of a column to a (getdateutc())

我想做的是设置EF值高的表格,我发现唯一可行的方法是使用 DbMigrations (向上和向下方法)。还有其他方法吗?

What I want to do is have EF set up tables with this value speficied, and the only way I've found that it's possible is to use DbMigrations (Up and Down methods). Are the any other ways ?

我有一个像这样的基类

 public abstract class BASE_AUDITED : BASE
 {              
      [IgnoreDataMember, IgnoreMap]
      public DateTime Created { get; set; }

      [IgnoreDataMember, IgnoreMap]
      public DateTime Modified { get; set; }

      [MaxLength(50)]
      [IgnoreDataMember, IgnoreMap]
      public string CreatedBy { get; set; }

      [MaxLength(50)]
      [IgnoreDataMember, IgnoreMap]
      public string ModifiedBy { get; set; }
 }

 public abstract class BASE 
 {
      [IgnoreMap]
      public int id { get; set; }
 }

以及一堆继承自它的类。
我想做的是能够在DBMigrations Up方法中访问模型(使用 fluentAPI 进行映射),并在其中编写循环照顾从 Base_audited

And a bunch of classes inheriting from it. What I'd like to do is be able to access the model (using fluentAPI for mapping)in the DBMigrations Up method, and write a loop there to take care of all the the objects inheriting from Base_audited

继承的所有对象。换句话说,我试图避免为我添加的每个对象

In other words I'm trying to avoid writing following code for each and every object I add,

AlterColumn("T70_AccountService.CONTACT", "TestClmn", c => c.DateTime(nullable: false, defaultValueSql: "(getutcdate())"));

但是像这样的东西

 var types = ReflectionHelper.TypesImplementingInterface(typeof (BASE_AUDITED));
            foreach (var type in types)
            {
               var tableName = Context.FindTableNameFor(type);
               AlterColumn(tableName , "Created", c => c.DateTime(nullable: false, defaultValueSql: "(getutcdate())"));
               AlterColumn(tableName , "Modified", c => c.DateTime(nullable: false, defaultValueSql: "(getutcdate())"));

            }

总之-我找不到映射到哪个表的对象

In short - I cannot find what table is the object mapped to in the DbMigrations Up method..

 var tableName = Context.FindTableNameFor(type);


推荐答案

我已经实现的解决方案可以在迁移配置中使用 种子方法,但需要一些开销(重新创建约束素),可以很好地工作:

The solution I've implemented, and that seems to work fine with some overhead (of recreating contrains) is to use the "Seed" method of the migration configuration:

  protected override void Seed(AccountServiceEntities context)
        {
            //  This method will be called after migrating to the latest version.

            #region SET Defaults for Audit Fields

            var types = ReflectionHelper.GetEnumerableOfType<BASE_AUDITED>();
            foreach (var type in types)
            {
                var method = typeof(ContextExtensions).GetMethod("GetTableName");
                var generic = method.MakeGenericMethod(type.GetType());
                var table = generic.Invoke(this, new object[] { context });

                var constraintName = string.Format("DF__{0}__", type.GetType().Name);

                CreateDefaultCronstraint(context, table, constraintName, "Created");
                CreateDefaultCronstraint(context, table, constraintName, "Modified");

            }

            #endregion...

这是修改后的Context扩展类,它从Context
公共静态类ContextExtensions
{

And here's the modified Context extentions class that extract the table name from the Context public static class ContextExtensions {

    public static string GetTableName<T>(this DbContext context) where T : class
    {
        var objectContext = ((IObjectContextAdapter)context).ObjectContext;
        return objectContext.GetTableName2<T>();
    }

    public static string GetTableName2<T>(this ObjectContext context) where T : class
    {
        var sql = context.CreateObjectSet<T>().ToTraceString();
        var regex = new Regex("FROM (?<table>.*) AS");
        var match = regex.Match(sql);

        var table = match.Groups["table"].Value;
        return table;
    }
}

这篇关于EF 5 Code First DbMigration自动化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆