Reputation: 3795
I have a simple Person View Model
public class PersonViewModel
{
public int ID {get;set;}
public String FirstName {get;set;}
public String LastName {get;set;}
}
The view has three fields
I have this function in my PersonService
which uses an EF6 datacontext which gets injected.
public IQueryable<Person> Search(Expression<Func<Person,bool>> predicate)
{
return dataContext.GetSet<Person>().Where(predicate);
}
Now my MVC Controller actually works with a PersonViewModel class
[HttpPost]
public ActionResult Search(PeopleSearchViewModel model)
{
if (ModelState.IsValid)
{
var listOfPersons= PersonService.Search(
//map viewmodel to model and search here)
//return the list and render a view etc...not important
}
}
So what I am wondering is whether it is a good idea if I can somehow take the PersonViewModel, create a Func<Person,bool>
predicate and pass it to the PersonService
for search, instead of using automapper to map my view model to domain model ?
Thanks
Upvotes: 1
Views: 596
Reputation: 4821
Firstly, you are passing type Func as the predicate to a function returning an IQueryable. You should actually be passing in an Expression<Func<Person, bool>>
so that whatever generates your query can actually inspect the function as an expression tree and generate SQL or something from it. If you don't, your query generator may end up loading your entire table and iterating manually (saw this happen with entity framework once).
On to your answer: I would make a function on your PeopleSearchViewModel
like so:
public Expression<Func<Person, bool>> ToExpression()
{
//this can be whatever your search query needs to be... I just did this quick and dirty
return p => p.FirstName == this.FirstName || p.LastName == this.LastName || p.ID == this.ID;
}
Then, simply pass the result of calling model.ToExpression()
in to your search function.
Upvotes: 2