简体   繁体   English

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

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

Background: I would like to use System.Linq.Dynamic library to post In/Contains query to MS SQL 背景:我想使用System.Linq.Dynamic库将In /包含查询发布到MS SQL

Please note I am trying to use System.Linq.Dynamic in generic function so that I could apply customer filter to any class having CustomerId(integer) property. 请注意,我试图在泛型函数中使用System.Linq.Dynamic,以便可以将客户过滤器应用于任何具有CustomerId(integer)属性的类。 Also CustomerId property could be nullable 而且CustomerId属性可以为空

All SO posts redirects me to this solution . 所有的SO帖子将我重定向到此解决方案 After implementing the same I keep getting this exception: "No generic method 'Contains' on type 'System.Linq.Enumerable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic." 执行完相同的操作后,我不断收到此异常:“类型'System.Linq.Enumerable'上没有通用方法'包含'与所提供的类型实参和参数兼容。如果该方法是非泛型的,则不应该提供任何类型实参。 “

And now this is how my code looks like : 现在这就是我的代码的样子

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

Could you please guide me where I am going wrong? 您能指导我哪里出问题了吗?

Because your MyUser.CustomerId property is nullable - you should pass nullable int array as customerIds in this case. 因为您的MyUser.CustomerId属性是可为空的-在这种情况下,您应将可为null的int数组作为customerIds传递。 For example: 例如:

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

or convert passed array to array of nullable ints: 或将传递的数组转换为可为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
}

Alternatives proposed by Ivan Stoev in comments (with them customerIds array can be regular int[] array, no need for it to be array of nullables): Ivan Stoev在评论中提出的替代方案(与它们一起使用, customerIds数组可以是常规的int[]数组,不需要将其为可为null的数组):

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

And this one will work in both cases (whether CustomerId is nullable or not): 并且这将在两种情况下都起作用(无论CustomerId是否可为空):

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

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

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