繁体   English   中英

使用System.Linq.Dynamic在或包含查询

[英]In or Contains query using System.Linq.Dynamic

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

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

所有的SO帖子将我重定向到此解决方案 执行完相同的操作后,我不断收到此异常:“类型'System.Linq.Enumerable'上没有通用方法'包含'与所提供的类型实参和参数兼容。如果该方法是非泛型的,则不应该提供任何类型实参。 “

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

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; }
}

您能指导我哪里出问题了吗?

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

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

或将传递的数组转换为可为null的int数组:

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在评论中提出的替代方案(与它们一起使用, customerIds数组可以是常规的int[]数组,不需要将其为可为null的数组):

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

并且这将在两种情况下都起作用(无论CustomerId是否可为空):

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

暂无
暂无

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

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