简体   繁体   English

无法翻译 EF Core Linq 表达式

[英]EF Core Linq expression could not be translated

I have an issue with an EF Core query when I'm filtering against a nullable Guid property, for example例如,当我针对可为空的 Guid 属性进行过滤时,我遇到了 EF Core 查询问题

public class Order 
{
  public Guid? MachineId {get;set;}
}

I'm trying to filter orders based on a list of MachineId s我正在尝试根据MachineId列表过滤订单

var machineIds // a list of Guids

var orders = _context.Orders.Where(x => machineIds.Contains(x.MachineId.GetValueOrDefault()));

The error I'm getting is我得到的错误是

System.InvalidOperationException : The LINQ expression 'DbSet<Orders>
        .Where(x => __machineIds_0
            .Contains(m.MachineId.GetValueOrDefault()))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I'm not sure how to express this query another way - can anyone help?我不确定如何以另一种方式表达这个查询 - 任何人都可以帮忙吗?

Converting the list of Guids to a list of nullable Guids resolves the issue (thanks mjwills ).将 Guid 列表转换为可为 null 的 Guid 列表解决了该问题(感谢mjwills )。

var machineIds = machines
  .Select(x =>  new Guid?(x.Id)); 

The EF Core query becomes EF Core 查询变为

var orders = _context.Orders.Where(x => machineIds.Contains(x.MachineId));

I'd suggest removing the use of .GetValueOrDefault() and make machineIds a list of nullable guids (rather than guids).我建议删除.GetValueOrDefault()的使用, .GetValueOrDefault()成为可空 guid(而不是 guid)的列表。

This might look like:这可能看起来像:

var machineIds = new List<Guid?>();

var orders = _context.Orders.Where(x => machineIds.Contains(x.MachineId));
_context.Orders.Where(order => MachineIds.Where(Id => Id == order.MachineId).Any())

This is untested.这是未经测试的。 Modifications might be necessary.可能需要进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM