ASP.NET search form - dynamic Linq to SQL?

前端 未结 3 1403
自闭症患者
自闭症患者 2021-02-10 04:27

I have a search form that allows users to search on several different fields in several different ways. Here is an example of my code.

var claims = from c in db.         


        
3条回答
  •  Happy的楠姐
    2021-02-10 05:24

    You could refactor some parts of the code by creating an extension method. Something like that :

    static class QueryableExtensions
    {
        private static MethodInfo StringContainsMethod;
        private static MethodInfo StringStartsWithMethod;
    
        static QueryableExtensions()
        {
            Type[] singleStringParam = new[] {typeof(string)};
            StringContainsMethod = typeof(string).GetMethod("Contains", singleStringParam);
            StringStartsWithMethod = typeof(string).GetMethod("StartsWith", singleStringParam);
        }
    
        public static IQueryable AppendTextFilter(this IQueryable queryable, Expression> memberSelector, string condition, string value)
        {
            Expression expression = null;
            switch (condition)
            {
                case "StartsWith":
                    expression = Expression.Call(
                                    memberSelector.Body,
                                    StringStartsWithMethod,
                                    Expression.Constant(value));
                    break;
    
                case "Equals":
                    expression = Expression.Equal(
                                    memberSelector.Body,
                                    Expression.Constant(value));
                    break;
    
                case "Contains":
                    expression = Expression.Call(
                                    memberSelector.Body,
                                    StringContainsMethod,
                                    Expression.Constant(value));
                    break;
    
                default:
                    throw new NotSupportedException(string.Format("'{0}' is not a supported condition", condition));
            }
    
            var lambda = Expression.Lambda>(
                            expression,
                            memberSelector.Parameters);
            return queryable.Where(lambda);
        }
    }
    

    You could then use it like that :

    var claims = db.Claims
                 .AppendTextFilter(c => c.companyFileID, ddlSearchField.Text, txtSearchBox.Text)
                 .AppendTextFilter(c => c.someOtherProperty, ddlOtherSearchField.Text, txtOtherSearchBox.Text)
                 ...;
    

提交回复
热议问题