且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

构建动态LINQ查询的***方式

更新时间:2023-12-04 23:47:04

好吧,它不是完全清楚你想要什么,但如果你想只添加其中,对于那些非空参数的条款,你可以做

Okay, it's not entirely clear what you want, but if you're trying to only add where clauses for the parameters which are non-null, you could do:

public IQueryable<Student> FindByAllStudents
    (int? id, string name, int? courseID, bool? isActive)
{    
    IQueryable<Student> query = db.Student;
    if (id != null)
    {
        query = query.Where(student => student.ID == id.Value);
    }
    if (name != null)
    {
        query = query.Where(student => student.Name.Contains(name));
    }
    if (courseID != null)
    {
        query = query.Where(student => student.CourseID == courseID.Value);
    }
    if (isActive != null)
    {
        query = query.Where(student => student.IsActive == isActive.Value);
    }
    return query;
}

我还没有试过,它的的可能的是LINQ to SQL的将由code感到困惑找到空值类型的值。您可能需要写code是这样的:

I haven't tried that, and it's possible that LINQ to SQL would get confused by the code to find the value of the nullable value types. You may need to write code like this:

    if (courseID != null)
    {
        int queryCourseID = courseID.Value;
        query = query.Where(student => student.CourseID == queryCourseID);
    }

这是值得尝试的简单形式,虽然第一:)

It's worth trying the simpler form first though :)

当然,这一切都变得有点恼火。一个有用的扩展方法可以让生活更简洁:

Of course, all this gets a bit irritating. A helpful extension method could make life more concise:

public static IQueryable<TSource> OptionalWhere<TSource, TParameter>
    (IQueryable<TSource> source,
     TParameter? parameter, 
     Func<TParameter, Expression<Func<TSource,bool>>> whereClause)
    where TParameter : struct
{
    IQueryable<TSource> ret = source;
    if (parameter != null)
    {
        ret = ret.Where(whereClause(parameter.Value));
    }
    return ret;
}

然后,您会使用这样的:

You'd then use it like this:

public IQueryable<Student> FindByAllStudents
    (int? id, string name, int? courseID, bool? isActive)
{    
    IQueryable<Student> query = db.Student
        .OptionalWhere(id, x => (student => student.ID == x))
        .OptionalWhere(courseID, x => (student => student.CourseID == x))
        .OptionalWhere(isActive, x => (student => student.IsActive == x));
    if (name != null)
    {
        query = query.Where(student => student.Name.Contains(name));
    }
    return query;
}

使用高阶函数这样可以得到,如果你不与它真的很舒服的,所以如果你没有做很多的查询这样你可能要坚持使用时间较长,但更简单的code混乱

Using a higher order function like this could get confusing if you're not really comfortable with it though, so if you're not doing very many queries like this you might want to stick with the longer but simpler code.