lexeme
lexeme

Reputation: 2973

Search action using linq predicate. ASP.NET MVC

I'm wondering how to implement search functionality?

Let's see how do I imagine about it. I will use employee model for the example. So employee holds rather standard properties: 'Id', EmployeeId, Name, Birthday.

My Repository object holds a method like:

IQueryable<T> Get(Expression<Func<T, Boolean>> predicate);

So then Search (belongs to EmployeeController) action would look like

[HttpPost]
public ViewResult Search(Guid Id, Guid EmployeeId, String Name, DateTime birthday)
{
    // call repository.get(x => x.Name == Name && x.Id == Id ... );
}

The Search view would then hold a form with textboxes corresponding to search criterias/action parameters.

But there the searching ability is coupled to the model/controller. So I would need to create similar action per controller.

How to make it in some better manner?

Thanks!

Upvotes: 0

Views: 1463

Answers (2)

Efe Kaptan
Efe Kaptan

Reputation: 465

1 - You can use ViewModel while passing your arguments to your action

[HttpPost]
public ViewResult Search(EmployeeViewModel model)
{
  //logic
}

2 - For a generic search functionality, you can use Dynamic Linq.

Upvotes: 1

devdigital
devdigital

Reputation: 34369

If you are saying that the predicate code is repeated across all calls to the repository, then you should either make that part of the repository, by creating a specific EmployeeRepository, that can either derive from your generic repository, or use it via composition:

public class EmployeeRepository : GenericRepository<Employee>
{
   public IEnumerable<Employee> GetEmployeesBySearch(string id, string name...)
   {
     return this.Get(x => x.Name == name && ...);
   }
}

Alternatively, you could consider the specification pattern. This separates the concern of selecting objects from the concern of which objects to select. There is an example with NHibernate here.

Upvotes: 0

Related Questions