在CSharpMigrationCodeGenerator中使用自定义MigrationOperation

时间:2018-01-19 07:48:02

标签: c# entity-framework-6 ef-migrations

我想为CSharpMigrationCodeGenerator创建自己的迁移操作,因此我创建了自己的MigrationOperation派生的迁移操作。

public class CustomMigrationOperation : MigrationOperation
{
    public CustomMigrationOperation() : base(null)
    {
        IsDestructiveChange = false;
    }

    public override bool IsDestructiveChange { get; }

    public override MigrationOperation Inverse => null;
}

定制的CSharpMigrationCodeGenerator。

public class CustomCSharpMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
    public override ScaffoldedMigration Generate(string migrationId, IEnumerable<MigrationOperation> operations, string sourceModel, string targetModel,
        string @namespace, string className)
    {
        var extendedOperations = operations.ToList();
        extendedOperations.Add(new CustomMigrationOperation());

        return base.Generate(migrationId, extendedOperations, sourceModel, targetModel, @namespace, className);
    }

    protected virtual void Generate(CustomMigrationOperation operation, IndentedTextWriter writer)
    {
        // do something
    }
}

当我在软件包管理器控制台中运行Add-Migration脚本时,我遇到以下异常:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'System.Data.Entity.Migrations.Design.CSharpMigrationCodeGenerator.Generate(System.Data.Entity.Migrations.Model.AddColumnOperation, System.Data.Entity.Migrations.Utilities.IndentedTextWriter)' has some invalid arguments
   at CallSite.Target(Closure , CallSite , CSharpMigrationCodeGenerator , Object , IndentedTextWriter )
   at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
   at System.Data.Entity.Migrations.Design.CSharpMigrationCodeGenerator.<>c__DisplayClass35.<Generate>b__27(Object o)
   at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
   at System.Data.Entity.Migrations.Design.CSharpMigrationCodeGenerator.Generate(IEnumerable`1 operations, String namespace, String className)
   at System.Data.Entity.Migrations.Design.CSharpMigrationCodeGenerator.Generate(String migrationId, IEnumerable`1 operations, String sourceModel, String targetModel, String namespace, String className)
   at Custom.Model.CustomCSharpMigrationCodeGenerator`1.Generate(String migrationId, IEnumerable`1 operations, String sourceModel, String targetModel, String namespace, String className) in 
   at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
   at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
   at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
The best overloaded method match for 'System.Data.Entity.Migrations.Design.CSharpMigrationCodeGenerator.Generate(System.Data.Entity.Migrations.Model.AddColumnOperation, System.Data.Entity.Migrations.Utilities.IndentedTextWriter)' has some invalid arguments

在对Github上的EntityFramework 6代码进行一些研究之后,我找到了应该负责调用生成器的Generate函数的行:

.Each<dynamic>(o => Generate(o, writer));

CSharpMigrationCodeGenerator on Github

我不明白为什么C#没有调用适当的Generate函数。

解决方法是从AddColumnOperation派生并覆盖Generate(AddColumnOperation操作,...)并专门处理CustomMigrationOperation。但这不仅仅是一种有效的解决方案。

1 个答案:

答案 0 :(得分:0)

最简单的答案是DLR无法确定方法。

作为概念验证的示例,这是一个简化的变体控制台应用程序,显示了完全相同的行为。

using MicrosoftGenerator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AddMigrationRunner {
    class Program {

        static void Main(string[] args) {
            var generator = (Generator) new Something.Deep.Somewhere.MyCustomGenerator(); // reverse casted simply to dictate the "angle" from which we are coming.

            // PMC:> Add-Migration MyMigrationName
            generator.AddMigration("MyMigrationName"); 
        }
    }
}
namespace MicrosoftGenerator {
    // meant to be a rough "clone" of: https://github.com/mono/entityframework/blob/master/src/EntityFramework/Migrations/Design/CSharpMigrationCodeGenerator.cs
    public class Generator {
        private List<MigrationOperation> operations = new List<MigrationOperation>() { };

        public Generator() {
            operations.Add(new AddColumnOperation());
        }
        public void AddMigration(string name) {
            Generate(name, operations);
        }
        public virtual void Generate(string migrationId, IEnumerable<MigrationOperation> operations) {
            Console.WriteLine("Up() method generating..");
            operations.Each<dynamic>(o => Generate(o));
        }


        protected void Generate(AddColumnOperation op) {
            Console.WriteLine("<AddColumnOperation> execute.");
        }
    }

    public class AddColumnOperation : MigrationOperation {}
    public class MigrationOperation {}


 //https://github.com/mono/entityframework/blob/master/src/Common/IEnumerableExtensions.cs
    public static class MicrosoftUtilities {
        public static void Each<T>(this IEnumerable<T> ts, Action<T> action) {
            foreach (var t in ts) {
                action(t);
            }
        }

    }
}

namespace Something.Deep.Somewhere {
    public class MyCustomGenerator : Generator {
        public MyCustomGenerator() : base() {

        }
        public override void Generate(string migrationId, IEnumerable<MigrationOperation> operations) {
            var extendedOperations = operations.ToList();
            extendedOperations.Add(new MyCustomOperation());

            base.Generate(migrationId, extendedOperations);
        }

        protected void Generate(MyCustomOperation op) {
            Console.WriteLine("<MyCustomOperation> execute.");
        }
    }
    public class MyCustomOperation : MigrationOperation {

    }
}

因此,通过将自定义.Each操作执行程序拆分为一个foreach,我们可以看到,如果进行了适当的编码,它确实可以正常工作。

            //operations.Each<dynamic>(o => Generate(o));
            foreach(var op in operations) {
                Type op_type = op.GetType();
                var actionT = typeof (Action<>).MakeGenericType(op_type);
                var methodInfo = this.GetType().GetMethod("Generate", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { op_type }, null);
                methodInfo.Invoke(this, new object[]{ op });
            }

在这一点上,我不胜枚举,以解释为什么带有有效对象和实例的委托操作无法自行解决。 我想这是一个很好的例子,说明了为什么您不应该懒惰地使用dynamic咳嗽 @microsoft。

如果不修改EntityFramework源代码,我看不出任何解决方法。 如果还不使用运行时绑定的Extension方法将其作为硬dynamic参数化操作执行,则可以使用<type>。因为如果将其保留为dynamic,它将保持运行时绑定。 如您所证明的那样(行之有效!),您可以修改其根Generate方法(如上述示例所示):

        public virtual void Generate(string migrationId, IEnumerable<MigrationOperation> operations) {
            Console.WriteLine("Up() method generating..");
            operations.Each<dynamic>(o => ((dynamic)this).Generate(o));
        }

请注意((dynamic)this)强制转换前缀。 P.s.我从here收集了这一决心。

有3件事:

  1. 感谢您发布此信息,这正是我所需要的
  2. 对不起,我没有解决办法
  3. 并希望在这里明确键入Intel的情况下,有思想的人可以向我们展示一种绕过此问题的方法,而无需在Microsoft帐户上开张罚单。

因此,如果您希望像我们俩一样保持代码干净,我能想到的唯一解决方案是不调用base.Generate(),而是实现其源代码的复制/粘贴;这样您就可以覆盖他们对.Each的扩展方法delegate的调用。对于nuget更新和将来的开发人员(不知道他们的工作),这显然是有问题的。

一个人必须变脏才能清洁。我一点都不喜欢。