【问题标题】:Dynamic Where clauses with multiple joins using Linq使用 Linq 的具有多个连接的动态 Where 子句
【发布时间】:2012-01-05 17:57:43
【问题描述】:

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

  • .Net 3.5
  • Linq-To-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>)”的类型参数。尝试明确指定类型参数。

这是我的 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”,并得到错误“和”无法识别。

感谢任何帮助。

谢谢。

【问题讨论】:

    标签: linq join conditional where-clause


    【解决方案1】:

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

    您希望获取 course_type_id 为空的行,但 = 比较不返回任何结果,因为 NULL 不是值,并且比较返回 UNKNOWN。我认为这是你“不正确的结果”的原因。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多