Entity Framework Code First & Search Criteria

前端 未结 2 1378
花落未央
花落未央 2020-12-13 03:22

So I have a model created in Entity Framework 4 using the CTP4 code first features. This is all working well together.

I am attempting to add an advanced search f

相关标签:
2条回答
  • 2020-12-13 03:35

    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.

    0 讨论(0)
  • 2020-12-13 03:41

    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.

    0 讨论(0)
提交回复
热议问题