使用Linq的具有多个联接的动态Where子句

时间:2012-01-05 17:57:44

标签: linq join conditional where-clause

我需要在具有多个连接的Linq语句中构建动态where子句。

  • .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子句,但Nullable 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,但它返回错误:

  

无法从用法推断出方法'System.Linq.Queryable.Where(System.Linq.IQueryable,System.Linq.Expressions.Expression&gt;)'的类型参数。尝试明确指定类型参数。

这是我的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
});

顺便说一下,我也尝试使用“System.Linq.Dynamic”使用字符串查询,并得到错误“和”无法识别。

感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:0)

具有可空类型变量的Linq谓词被转换为SQL谓词= NULL。但这与应有的完全不同:IS NULL

您希望得到course_type_id为空的行,但是=比较不返回结果,因为NULL不是值,比较返回UNKNOWN。我认为这是导致“错误结果”的原因。

如果这是您的问题,可以找到修复here

相关问题