2012-01-05 10 views
0

Linq文に動的なwhere節を複数の結合で構築する必要があります。Dynamic Where Linqを使用して複数の結合を持つ節

  • .NET 3.5
  • LINQのからSQLへ

私は、LINQの文のこれらの着信のパラメータを持っている、唯一の "UID" が必要です。

int uid = 23702; // <-- Only one Required 
string courseNumber = ""; 
string title = ""; 
int? categoryId = null; 
int? typeId = null; 

私はLinqPadでこれをテストしてきたと私は場所にすべてのWHERE句で動作するようにクエリを得ている一方で、Null許容int型のパラメータが間違った結果を返す終わります。

は、ここに私のLINQ文のです:

var ci = course_instances; 

var query = courses.Join(ci, 
    c => c.course_id, 
    i => i.course_id, 
    (c, i) => new 
{ 
    c = c, 
    i = i 
}).Join(user_courses, 
    temp => temp.i.instance_id, 
    uc => uc.instance_id, 
    (temp, uc) => new 
{ 
    temp = temp, 
    uc = uc 
}) 
.Where (temp1 => (temp1.uc.uid == uid)) 
.Where (temp1 => (temp1.temp.c.course_number.Contains(courseNumber))) 
.Where (temp1 => (temp1.temp.c.title.Contains(title))) 
//.Where (temp1 => (temp1.temp.c.course_type_id == typeId)) 
//.Where (temp1 => (temp1.temp.c.course_category_id == categoryId)) 
.Select (temp1 => new CourseSearchMyCourses 
{ 
    // snipped the many properties 
}); 

私はPredicateBuilderを使用してみましたが、それはエラーを返しました:

The type arguments for method 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

ここに私のPredicateBuilder LINQの試みです:

var conditions = PredicateBuilder.True<user_course>(); 
conditions = conditions.And(c => c.uid == uid); 

var ci = course_instances; 

var query = courses.Join(ci, 
    c => c.course_id, 
    i => i.course_id, 
    (c, i) => new 
{ 
    c = c, 
    i = i 
}).Join(user_courses, 
    temp => temp.i.instance_id, 
    uc => uc.instance_id, 
    (temp, uc) => new 
{ 
    temp = temp, 
    uc = uc 
}) 
.Where (conditions) 

.Select (temp1 => new CourseSearchMyCourses 
{ 
    // snipped the many properties 
}); 

BTW 、私も "System.Linq.Dynamic"を使用して文字列クエリを使用しようとし、エラーを持って "と"再ありません認識された。

何か助けていただければ幸いです。

ありがとうございました。

答えて

0

null可能な型変数を持つLinq述部は、SQL述語= NULLに変換されます。しかし、それはそれがすべきこととはまったく異なります:IS NULL

course_type_idが空の行を取得すると予想されますが、NULLは値ではないため比較がUNKNOWNを返すため、=比較結果は返されません。私はそれがあなたの「間違った結果」の原因だと思う。

これが問題の場合は、hereという修正があります。

関連する問題