2017-11-27 7 views
1

を使用してクエリが含まれています:私は/に投稿するSystem.Linq.Dynamicライブラリを使用したいは、MS SQLInまたは背景System.Linq.Dynamic

にクエリが含まれています、私はシステムを使用しようとしていますのでご注意ください。私はCustomerId(整数)プロパティを持つ任意のクラスに顧客のフィルタを適用することができるように汎用関数のLinq.Dynamic。また、CustomerIdプロパティはnull可能である可能性があります

すべての投稿は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; } 
} 

私が間違っているつもりですどこが私を導いてもらえ:

そして今、これは私のコードはどのように見えるかですか?

+0

これは「T is int」のときにのみ機能すると思いますが、ジェネリック関数は非ジェネリックではなくなりますか? – oerkelens

+0

それは事実ではありません。顧客IDを持つどのクラスでも動作します。 –

答えて

3

MyUser.CustomerIdプロパティがnullableであるため、この場合はNULL入力可能な配列を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の配列に渡された配列を変換します。彼らとコメント(中イワンStoevが提案し

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

代替はcustomerIds配列は、通常のint[]配列、それが不要になることができます)nullablesの配列である:

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

そして、この1)はCustomerIdがNULL可能であるかどうか(両方のケースで動作します。

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

またはプロパティを 'int''' '@ 0.Contains(outerIt.CustomerId.Value)' 'または' '@ 0.Contains(int(outerIt.CustomerId))」に変換してください。 –

+0

@IvanStoev last proposal(" @ 0 .Contains(int(outerIt.CustomerId)) ")は動作していないようです。 – Evk

+0

ありがとうございます!それは魅力のように働いた。私が得た例外は役に立たなかった。 –