【问题标题】:Simple Linq Select not working简单的 Linq 选择不起作用
【发布时间】:2018-03-06 23:55:56
【问题描述】:

我正在尝试选择一个整数列表,但它引发了异常。

异常消息:System.ArgumentException:类型表达式 'System.Collections.Generic.IAsyncEnumerable1[System.Int32]' 不能 用于类型参数 'System.Collections.Generic.IAsyncEnumerable1[System.Object]' 的 方法 'System.Collections.Generic.IAsyncEnumerable1[MyProject.Model.Entities.MyTable] 演员表' 参数名称:arg0

重现步骤

型号

public class MyTable { 
  public int MyTableId { get; set; } 
  public int SomeKey { get; set; } 
  public int MyFieldIntegerIWant { get; set; } 
} 

运行下面的查询(或类似的查询):

int keyId;
var ids = await context.MyTable.AsNoTracking()
        .Where(x => x.SomeKey.Equals(keyId))
        .Select(x => x.MyFieldIntegerIWant)
        .ToListAsync();

更多技术细节

EF Core 版本:1.1.0

数据库提供者:Microsoft.EntityFrameworkCore.SqlServer

操作系统:Windows 7

IDE:Visual Studio 2015

更新:

The issue had something to do with EF Plus' QueryFilters https://github.com/zzzprojects/EntityFramework-Plus/issues/133

【问题讨论】:

  • 我猜SomeKey不是原始类型keyId不是原始类型。请分享您在集合MyTable 中定义的模型。以及keyId 的类型和值。
  • 试试x.SomeKey == keyId)
  • AsNoTracking() 是做什么的?
  • @EpicKip - 这是 EF 内置的,它确保上下文不会跟踪返回的实体。如果您不打算将修改推送回上下文,这是非常有益的,因为它可以提高性能。
  • 使用@thejason 提供给我们的附加信息,这个问题不是由我们的库引起的,而是因为 Entity Framework Core 没有正确处理 Cast 方法。

标签: c# linq asp.net-core entity-framework-core entity-framework-plus


【解决方案1】:

在与@thejason 讨论后,

问题不是由 Entity Framework Plus 引起的,而是 EF Core 处理强制转换的方式。

可以使用以下代码轻松重现该问题:

using (var ctx = new CurrentContext())
{
    int keyId = 1;

    var ids = ctx.MyTables
        .Cast<IMyTable>()
        .Cast<MyTable>()
        .Where(x => x.SomeKey.Equals(keyId))
        .Select(x => x.MyFieldIntegerIWant)
        .ToList();
}

转换方法将在 EF Core 2.x 中修复

【讨论】:

    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2021-06-22
    相关资源
    最近更新 更多