I am developing an Asp.net Core 2 MVC project as follows. I will keep the code snippet as simple as possible by removing the parts that we should be familiar with.
-
Entity model
public class Customer { public string Id { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string Country { get; set; } } -
Database context
public class AppDbContext : DbContext { public DbSet<Customer> Customers { get; set; } public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } } -
Auxiliary class for searching by country, company name, and others
public class Search { public enum Options { [Display(Name="By Country")] ByCountry = 1, [Display(Name = "By Company Name")] ByCompanyName = 2, // in the future there will be other items appended } public AppDbContext Context { get; } public IDictionary<Options, Func<string, IEnumerable<Customer>>> SearchMethods { get; } public Search(AppDbContext context) { Context = context; SearchMethods = new Dictionary<Options, Func<string, IEnumerable<Customer>>>() { [Options.ByCountry] = x => Context.Customers .Where(c => c.Country.ToLower().Contains(x.ToLower())) .ToList(), [Options.ByCompanyName] = x => Context.Customers .Where(c => c.CompanyName.ToLower().Contains(x.ToLower())) .ToList() // in the future there will be other items appended }; } }
Search allows me to avoid hard-coded literal string in both controllers and views. Here are the examples:
-
Controller
public class HomeController : Controller { public Search S { get; } public HomeController(Search s) => S = s; [HttpPost] public IActionResult Search(string criteria, Search.Options searchBy) => View(S.SearchMethods[searchBy](criteria)); } -
View
<input name="criteria" /> <select name="searchBy" asp-items="Html.GetEnumSelectList<Search.Options>()"></select>
Questions
I realize that gradually adding new elements to Options enumeration and adding new items to SearchMethods dictionary properties will not produce versioning issue as long as I can make sure the elements of Options are kept numerically in the same orders.
Now my concern is whether there are any drawbacks with this approach? For example about performance issue, scalability issue because there is an instance of dictionary SearchMethods per instance of Search.
Any comments and suggestions are welcome.
Aucun commentaire:
Enregistrer un commentaire