Last active
June 14, 2018 21:00
-
-
Save Deathspike/9a578e59e62c09893808 to your computer and use it in GitHub Desktop.
ASP.NET MVC Using a Context in a DataController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class DataController : Controller | |
{ | |
private IContext _context; | |
#region Constructor | |
protected DataController() | |
{ | |
_context = new Context(); | |
} | |
#endregion | |
#region Contract | |
[ContractInvariantMethod] | |
private void ObjectInvariant() | |
{ | |
Contract.Invariant(_context != null); | |
} | |
#endregion | |
#region Properties | |
public IContext Context | |
{ | |
get { return _context; } | |
protected set { _context = value ?? _context; } | |
} | |
#endregion | |
#region Overrides of Controller | |
protected override void Dispose(bool disposing) | |
{ | |
if (disposing) | |
{ | |
Context.Dispose(); | |
} | |
base.Dispose(disposing); | |
} | |
protected override void OnActionExecuted(ActionExecutedContext filterContext) | |
{ | |
if (filterContext != null && filterContext.Controller != null) | |
{ | |
filterContext.Controller.ViewBag.Context = Context; | |
} | |
base.OnActionExecuted(filterContext); | |
} | |
#endregion | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MachineController : DataController | |
{ | |
[HttpGet] | |
public ActionResult Index(int id = 0) | |
{ | |
var machine = id == 0 ? null : Context.Machines.FirstOrDefault(x => x.Id == id); | |
return new ContentResult { Content = machine == null ? "No machine :-(" : machine.Name }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment