gpt4 book ai didi

c# - 在 CSharpMigrationCodeGenerator 中使用自定义 MigrationOperation

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:23 25 4
gpt4 key购买 nike

我想为 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 代码进行一些研究后,我找到了应该负责调用生成器的生成函数的行:

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

CSharpMigrationCodeGenerator on Github

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

解决方法是派生自 AddColumnOperation 并覆盖 Generate(AddColumnOperation operation, ...) 并在那里专门处理 CustomMigrationOperation。但这与其说是一个有用的解决方案,不如说是一种技巧。

最佳答案

简短的回答是 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 Action 执行器拆分为一个 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 });
}

我现在无法解释为什么具有有效对象和实例的委托(delegate)操作无法自行解析。我想这是一个很好的例子,说明为什么你不应该使用 dynamic以一种懒惰的方式。 咳嗽 @microsoft。

如果不修改 EntityFramework 源代码,我看不到任何解决此问题的方法。dynamic的使用没关系,如果他们不使用运行时绑定(bind)扩展方法来执行该方法作为硬 <type>参数化 Action ;因为如果它被保存为 dynamic它将保持运行时绑定(bind)。事实证明(它有效!)如果你修改他们的根 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)类型转换前缀。附言我从 here 中收集了这种决心.

所以 3 件事:

  1. 感谢您发布这个,这正是我所需要的
  2. 抱歉,我没有解决方案
  3. 希望在此处明确输入此 Intel 后,有头脑的人可以向我们展示一种绕过此问题的方法,而无需在 Microsoft 帐户上开票。

所以如果你想像我们一样保持代码干净,我能想到的唯一解决方案是不调用 base.Generate() , 而不是实现其源代码的复制/粘贴;这样你就可以覆盖他们的扩展方法 .Each调用 delegate .这对于 nuget 更新和不知道自己在做什么的 future 开发人员来说显然是有问题的。

人必须先弄脏才能干净。我有点不喜欢这一点。

关于c# - 在 CSharpMigrationCodeGenerator 中使用自定义 MigrationOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48336342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com