[英]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.