Entity Framework Code First & Search Criteria

眉间皱痕 提交于 2019-11-28 17:07:11

So after some hours of work on this problem (and some help from our friend Google) I have found a workable solution to my problem. I created the following Linq expression extension:

using System;
using System.Linq;
using System.Linq.Expressions;

namespace MyCompany.MyApplication
{
    public static class LinqExtensions
    {
        public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
        {
            if (condition)
                return source.Where(predicate);
            else
                return source;
        }
    }
}

This extension allows for a Linq query to be created like this:

var products = context.Products.WhereIf(!String.IsNullOrEmpty(name), p => p.Name == name)
                               .WhereIf(startDate != null, p => p.CreatedDate >= startDate)
                               .WhereIf(endDate != null, p => p.CreatedDate <= endDate);

This allows each WhereIf statement to only affect the results if it meets the provided condition. The solution seems to work, but I'm always open to new ideas and/or constructive criticism.

John,

Your solution is absolutely awesome! But, just to share, I have been using this method above until I see your ideia.

var items = context.Items.Where(t => t.Title.Contains(keyword) && !String.IsNullOrEmpty(keyword));

So, it seems not to be the best solution for this, but for sure it is a way around.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!