LinQ query Simple Where clause and many filter criteria

.net c# ef-code-first entity-framework-6 linq

Question

I need to filter data entity but there is no predefined columns, which I will have to filter.

public class EventDocument
{
    public string ID1 { get; set; }
    public int ID2 { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Number { get; set; }
    public virtual ICollection<Event> Events { get; set; }
}

I created all needed properties: SearchFirstName, SearchLastName, SearchNumber

And now I am trying to filter EventDocument by these parameters entered by user. If user enters value into SearchFirstName, my query will look like this:

var query = from b in DBContext.EventDocuments
                    where b.FirstName.Contains(SearchFirstName)
                    select b;

If user enters values to SearchFirstName and SearchLastName, my query will look like this:

var query = from b in DBContext.EventDocuments
                        where b.FirstName.Contains(SearchFirstName) 
                        && b.LastName.Contains(SearchLastName)
                        select b;

And how to construct query if I don't know - which filed user will fill? Maybe he will enter value to SearchLastName and SearchNumber...

1
2
4/26/2018 6:44:39 AM

Accepted Answer

Predicate Builder is an effective way.

Put following code in static PredicateBuilder class,

 public static Expression<Func<T, bool>> ContainsPredicate<T>(string memberName, string searchValue)
        {
            var parameter = Expression.Parameter(typeof(T), "m");
            var member = Expression.PropertyOrField(parameter, memberName);
            var body = Expression.Call(
                member,
                "Contains",
                Type.EmptyTypes, // no generic type arguments
                Expression.Constant(searchValue)
            );
            return Expression.Lambda<Func<T, bool>>(body, parameter);
        }

In your cs file,

var filterResults = PredicateBuilder.ContainsPredicate<Employee>(columnName, searchName);

And yourLinqQuery.Where(filterResults);

For Reference: Predicate Builder Details

2
7/18/2017 12:15:50 PM

Popular Answer

You could do something like this

var query = DBContext.EventDocuments;

if(!string.IsNullOrEmpty(SearchFirstName))
{
    query = query.Where(x => x.FirstName.Contains(SearchFirstName));
}
if(!string.IsNullOrEmpty(SearchLastName))
{
    query = query.Where(x => x.LastName.Contains(SearchLastName));
}

var result = query.ToList();

and building your query based on what conditions you need.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow