【发布时间】: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