Entity Framework Code First & Search Criteria

前端 未结 2 1379
花落未央
花落未央 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: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 WhereIf(this IQueryable source, bool condition, Expression> 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.

提交回复
热议问题