2016-04-28 85 views
0

我需要使用我的自定义迁移基地CustomMigration从套件管理器控制台搭建add-migration进行脚手架迁移,这是从DbMigration派生的。具有自定义迁移基地的实体框架添加迁移脚手架

public partial class NewMigration: CustomMigration 
{ 
    public override void Up() 
    { 
    } 

    public override void Down() 
    { 
    } 
} 

如果需要,我可以使用不同的命令。我没有任何PowerShell脚本技能。我怎样才能做到这一点?

回答

2

我创建了一个生成我的迁移的新类:

public class AuditMigrationCodeGenerator : CSharpMigrationCodeGenerator 
{ 
    protected override void WriteClassStart(string @namespace, string className, IndentedTextWriter writer, string @base, bool designer = false, IEnumerable<string> namespaces = null) 
    { 
     @base = @base == "DbMigration" ? "AuditMigration" : @base; 
     var changedNamespaces = namespaces?.ToList() ?? new List<string>(); 
     changedNamespaces.Add("Your.Custom.Namespace"); 
     base.WriteClassStart(@namespace, className, writer, @base, designer, changedNamespaces); 
    } 
} 

在Configuration.cs:

internal sealed class Configuration : DbMigrationsConfiguration<EfDataAccess> 
{ 
    public Configuration() 
    { 
     this.AutomaticMigrationsEnabled = false; 
     CodeGenerator = new AuditMigrationCodeGenerator(); 
    } 
} 

它会使用自定义的代码生成器,它产生与我期望的自定义​​迁移基地的迁移。

欲了解更多信息:https://romiller.com/2012/11/30/code-first-migrations-customizing-scaffolded-code/

0
  1. 运行命令add-migration NewMigration。它将添加名为“NewMigration”的新迁移。如果在模型中没有变化,迁移将是空的:

    public partial class NewMigration : DbMigration 
    { 
        public override void Up() 
        { 
        } 
    
        public override void Down() 
        { 
        } 
    } 
    
  2. 更改基类NewMigration来CustomMigration:

    public partial class NewMigration : CustomMigration 
    { 
        public override void Up() 
        { 
        } 
    
        public override void Down() 
        { 
        } 
    } 
    
  3. 修改NewMigration如你所愿
  4. 运行update-database申请移民
+0

感谢的答案,但是这就是我们现在做的,这是麻烦的,因为我们做每天约10迁移新项目。我们需要在每次迁移时进行自定义初始化和逻辑处理,例如审计。所以这对我们来说不是可以接受的选择,并且希望没有定制迁移的脚手架来防止初始化错误。 –