What I did on my system was to create a common Controller
that implements the search method. Something like this:
public abstract class Controller<TSource> : System.Web.Mvc.Controller
where TSource: class, IPesquisavel, new()
{
protected MeuContext db = new MeuContext();
public ActionResult Pesquisar(String termo)
{
var lista = db.Set<TSource>().Where(s => s.TermoPesquisa.Contains(termo)).ToList();
return View(lista);
}
}
View you can put in Views/Shared
(a little more complex to implement), or make a View Pesquisar.cshtml
for each Controller who has this search.
Implement IPesquisavel
like this:
public interface IPesquisavel
{
String TermoPesquisa { get; }
}
The Model that can receive this search looks like this:
public class MeuModel
{
...
public String Nome { get; set; }
public String Descricao { get; set; }
[DisplayName("Termo de Pesquisa")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public String TermoPesquisa
{
// No get, coloque os campos que interessam pra pesquisa, separados
// por vírgula. Por exemplo, Nome e Descricao
get { return Nome + ", " + Descricao; }
private set { }
}
}
When generating Migration , the Entity Framework does not understand that it is a calculated field. Comment on his generation and write in hand:
public partial class TestePesquisavel : DbMigration
{
public override void Up()
{
// AddColumn("dbo.MeuModels", "TermoPesquisa", c => c.String());
Sql("ALTER TABLE dbo.MeuModels ADD TermoPesquisa AS Nome + ', ' + Descricao");
}
public override void Down()
{
// DropColumn("dbo.MeuModels", "TermoPesquisa");
Sql("ALTER TABLE dbo.MeuModels drop column TermoPesquisa");
}
}