gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:46:51 25 4
gpt4 key购买 nike

背景:我想使用 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; }
}

你能告诉我哪里出错了吗?

最佳答案

因为您的 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 在评论中提出的替代方案(customerIds 数组可以是常规的 int[] 数组,不需要是可空数组):

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

这个在两种情况下都有效(无论 CustomerId 是否可为空):

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

关于c# - 在或包含查询使用 System.Linq.Dynamic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47507255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com