LINQ to SQL, Generalization
I'm struggling a bit to figure this out.
I am working on an ASP.NET MVC project using LINQ to SQL for my data layer. The database consists of 10 or more different "exception" tables, for example. ".LADM Exceptions", ".USB Exceptions", ".GPO Exceptions". Basically these tables keep track of user + machine information to relax various security procedures.
My LINQ to SQL model is created. I have different classes for every table I have access to. However, I'm not sure how to use them in a controller without having to generate separate controller actions for each type of exception. For an action, List
I want to do something like this:
// Example Request: /Exceptions/List/ladm
// Routing: Controller = "Exceptions", Action = "List", type = "ladm"
// Controller Action:
public ActionResult List(string type)
{
string viewname = "List-" + type; // refer to "List-ladm" view.
if(type == "ladm")
{
var items = _repository.ListAllLADMExceptions();
}
return View(viewname, items);
}
My repository implements methods ListAll<XXXXXX>Exceptions
for each table. Is there a way to avoid 10 different if / else statements? It looks ugly and I'm sure there is a better way that I can't think of. Perhaps I am approaching him from the wrong angle.
Any suggestions would be greatly appreciated.
Thank.
source to share
You can try the dynamic dispatch method using reflection (which is quite expensive in terms of performance):
object items = _repository.GetType().GetMethod("ListAll"+type+"Exceptions")
.Invoke(_repository, null);
I would write an instruction switch
(not if/else
) for 10 cases. It's not so bad.
switch (type) {
case "ladm": return View("ladm", _repository.ListAllLADMExceptions());
case "....": return View(....);
}
source to share
A typical pattern is one controller per table. How about redistributing variability across multiple controller classes using a common base class? Something like that:
public abstract class ExceptionsBaseController<T> : Controller where T:class
{
protected abstract Table<T> ExceptionsTable { get; }
public virtual ActionResult List()
{
var items = ExceptionsTable;
return View(items);
}
}
One benefit I see would be easier to handle differences between exception classes and add new ones. It probably won't help your overall code string count, but maybe it can spark ideas.
source to share