【问题标题】:In or Contains query using System.Linq.Dynamic在或包含使用 System.Linq.Dynamic 的查询
【发布时间】:2017-11-27 09:11:17
【问题描述】:

背景:我想使用 System.Linq.Dynamic 库将 In/Contains 查询发布到 MS SQL

请注意,我正在尝试在通用函数中使用 System.Linq.Dynamic,以便我可以将客户过滤器应用于任何具有 CustomerId(integer) 属性的类。 CustomerId 属性也可以为空

所有 SO 帖子都将我重定向到 this solution。在实现相同的功能后,我不断收到此异常:“类型'System.Linq.Enumerable'上的通用方法'Contains'与提供的类型参数和参数兼容。如果方法是非通用的,则不应提供类型参数。 "

现在这就是我的代码的样子

public static IQueryable<T> ApplyCustomerFilter<T>(this IQueryable<T> collection, int[] customerIds)
{
    return collection.Where("@0.Contains(outerIt.CustomerId)", customerIds);
}


public class MyUser : IdentityUser
{    
    [Required]
    [MaxLength(50)]
    public string FirstName { get; set; }
    [Required]
    [MaxLength(50)]
    public string LastName { get; set; }
    public int? CustomerId { get; set; }
    [ForeignKey(nameof(CustomerId))]
    public virtual Customer Customer { get; set; }
}

你能指导我哪里出错了吗?

【问题讨论】:

  • 我猜这只有在T is int 时才有效,使得泛型函数相当非泛型?
  • 这不是真的。它适用于任何具有客户 ID 的类。

标签: c# linq entity-framework-6


【解决方案1】:

因为您的 MyUser.CustomerId 属性是可空的 - 在这种情况下,您应该将可空的 int 数组作为 customerIds 传递。例如:

public static IQueryable<T> ApplyCustomerFilter<T>(
    this IQueryable<T> collection, 
    int?[] customerIds) { // < - note here
        return collection.Where("@0.Contains(outerIt.CustomerId)", customerIds);
} 

或将传递的数组转换为可为空的整数数组:

public static IQueryable<T> ApplyCustomerFilter<T>(
    this IQueryable<T> collection, 
    int[] customerIds) {
        return collection.Where("@0.Contains(outerIt.CustomerId)",
             customerIds.Cast<int?>()); // <- note here
}

Ivan Stoev 在 cmets 中提出的替代方案(customerIds 数组可以是常规的int[] 数组,不需要它是可空数组):

"@0.Contains(outerIt.CustomerId.Value)" 

而且这个在两种情况下都可以工作(CustomerId 是否可以为空):

"@0.Contains(Int32(outerIt.CustomerId))"

【讨论】:

  • 或将属性转换为int - "@0.Contains(outerIt.CustomerId.Value)""@0.Contains(int(outerIt.CustomerId))"
  • @IvanStoev 最后的提案(“@0.Contains(int(outerIt.CustomerId))”)似乎不起作用。
  • 谢谢!这就像一个魅力。我得到的异常没有帮助。
  • @IvanStoev,与Int32(outerIt.CustomerId) 合作,谢谢。
  • @shobhitvaish 看看 Ivan 提供的替代品,我认为它们更好(尤其是最后一个)。
猜你喜欢
  • 1970-01-01
  • 2014-01-01
  • 2018-04-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
相关资源
最近更新 更多