public

  • Download Gist
EF4 Code First template Global.asax.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
using System;
using System.Configuration;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.WebPages.Compilation;
using MyApp.Fixtures;
using MyApp.Models;
using MyApp.Services;
 
namespace MyApp
{
public class Db : DbContext
{
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
}
 
public class App : System.Web.HttpApplication
{
const string SessionKey = "Db.Session";
 
public static Db Db
{
get
{
return (Db)HttpContext.Current.Items[SessionKey];
}
}
 
public App()
{
BeginRequest += MvcApplication_BeginRequest;
AuthenticateRequest += MvcApplication_AuthenticateRequest;
EndRequest += MvcApplication_EndRequest;
}
 
void MvcApplication_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Items[SessionKey] = new Db();
}
 
void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Path.Contains("assets/"))
return;
AccountService.AuthenticateRequest();
}
 
void MvcApplication_EndRequest(object sender, EventArgs e)
{
var disposable = HttpContext.Current.Items[SessionKey] as IDisposable;
if (disposable != null)
disposable.Dispose();
}
 
protected void Application_Start()
{
Database.SetInitializer<Db>(new DbInitializer());
 
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
 
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
 
public static void RegisterRoutes(RouteCollection routes)
{
// turn off the unnecessary file exists check
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("assets/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
 
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyApp.Controllers" }
);
 
}
 
}
 
}

Example: var user = App.Db.Users.Find(id);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.