I have some Database-First MVC3 project that is actually an envelope for around 30 tables with CRUD operations.
There is EF5 with standard DBContext class and a DBSet for every table.
The Linq2SQL is used for CRUD operations.
Every table is implemented in a separate controller with Index action that returns View, and a number of Json actions for CRUDs.
Right now, to optimize code I use C# type templates and extension methods.
Is it worth to implement there IoC patterns (NInject?, UnitOfWork?) just to optimize my code further and to remove code repetitiveness?
Do I rise code readability when I pool out all CRUD actions to IoC Reporitory/DBContext factory?
public class tblCurrencyController : MvcApplication2.Controllers.AllInOneController<tblCurrency> { }
public class tblCountryController : MvcApplication2.Controllers.AllInOneController<tblCountry> { }
public class tblPriceLevelController : MvcApplication2.Controllers.AllInOneController<tblPriceLevel> { }
public class tblJobController : MvcApplication2.Controllers.AllInOneController<tblJob> { }
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class AllInOneController<T> : MyAuthenticationController where T : class, KeyValueSupported, new()
{
private MyDBContext context = new MyDBContext();
public ActionResult Index()
{
var model = new AllInOneModel() {
TypeName = typeof(T).AssemblyQualifiedName,
Items = context.Set<T>().ToList()
};
return View("AllInOneView", model);
}
[HttpPost]
public ActionResult Edit(T model)
{
Dictionary<string, string> errors = null;
var itm = context.Set<T>().AsEnumerable().FirstOrDefault(x => x.Key == model.Key);
if (itm != null)
{
itm.Value = model.Value;
context.Entry(itm).State = EntityState.Modified;
errors = Helpers.ValidateJsonModel(context);
}
else
{
errors = new Dictionary<string, string>();
errors.Add("genex", string.Format(Helpers.Resource("generr_item_not_found"), model.Key));
}
return JsonNet(errors);
}
[HttpPost]
public ActionResult Create(T model)
{
Dictionary<string, string> errors = null;
var items = context.Set<T>();
var newitemId = items.Any() ? items.AsEnumerable().Max(x => x.Key) : 0;
newitemId++;
context.Set<T>().Add(new T() { Key = newitemId, Value = model.Value });
errors = Helpers.ValidateJsonModel(context);
return JsonNet(errors);
}
public ActionResult Delete(string itemId)
{
Dictionary<string, string> errors = null;
int parsedItemId = int.Parse(itemId);
var item = context.Set<T>().AsEnumerable().Single(x => x.Key == parsedItemId);
context.Set<T>().Remove(item);
errors = Helpers.ValidateJsonModel(context);
return JsonNet(errors, JsonRequestBehavior.AllowGet);
}
}