本文介绍了Dapper抛出“ DynamicMethod的无效类型所有者”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试使用Dapper.net,但我很喜欢。我不喜欢的是当我尝试批量插入实体时抛出以下错误:

So I'm trying to use Dapper.net and I'm liking it. What I'm not liking is when I try to batch-insert entities and I get the following error thrown:

DynamicMethod的无效类型所有者。

这种情况在我完全正常的情况下会发生像这样运行我的查询:

This happens in a completely normal situation when I run my query like this:

        string sql = @" INSERT INTO XXX
                        (XXXId, AnotherId, ThirdId, Value, Comment)
                        VALUES
                        (@XXXId, @AnotherId, @ThirdId, @Value, @Comment)";

        var parameters = command
            .MyModels
            .Select(model => new
            {
                XXXId= model.XXXId,
                AnotherId= model.AnotherId,
                ThirdId= model.ThirdId,
                Value = model.Value,
                Comment = model.Comment
            })
            .ToArray();

...

sqlConnection.Query(sql, parameters, commandType: commandType, transaction: transaction)

我发现了由遇到相同问题的人开始,但问题似乎是.NET版本(3.5),但我正在运行.NET 4.5,但我不知道是什么问题。

I found the following SO-thread started by someone having the same problem BUT the issue there seems to have been the .NET version (3.5) but I'm running .NET 4.5 and I can't figure out what the problem is.

有什么建议吗?

推荐答案

由于此方案使用 Query [< T>] 不期望参数的数组/序列。 Execute 调用路径确实会期望这样做,并自动展开数据,对每个项目执行一次SQL-但这不是这种情况。 Query [< T>] ,因此它尝试创建绑定到 array 的动态方法(在您的情况下),这不是允许的。代码可能应该更早地检测到这一点,然后说不,那是不允许的。

It fails because this scenario using Query[<T>] isn't expecting an array / sequence of parameters. The Execute call-path does expect this, and unrolls the data automatically, executing the SQL once per item - but this isn't the case for Query[<T>], so it tries to create the dynamic method bound to the array (in your case), which isn't allowed. The code should probably detect this much earlier, and just say "nope, that isn't allowed".

可能想要更改您的 .ToArray() .Single()

下一次构建后,这将变得更加清晰;以下步骤:

This will be clearer after the next build; the following passes:

    public void SO30435185_InvalidTypeOwner()
    {
        try {
            // not shown for brevity: something very similar to your code
            Assert.Fail();
        } catch(InvalidOperationException ex)
        {
            ex.Message.IsEqualTo("An enumerable sequence of parameters (arrays, lists, etc) is not allowed in this context");
        }
    }

这篇关于Dapper抛出“ DynamicMethod的无效类型所有者”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:14