Skip to content

Instantly share code, notes, and snippets.

@jkresner
Created October 4, 2012 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkresner/3835134 to your computer and use it in GitHub Desktop.
Save jkresner/3835134 to your computer and use it in GitHub Desktop.
Cause EF5 context to create tables on Mvc App Start
public class UsersContext : DbContext
{
public UsersContext()
: base("cf5WebContext")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
//-- Drop/recreate db if model changes
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<cf5.Web.Models.cf5WebContext>());
//-- Cause DbContext to be initialized so the model is created when our app starts
var first = new cf5.Web.Models.cf5WebContext().PartnerCalls.FirstOrDefault();
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("cf5WebContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
<configSections>
<!-- Don't event need entityFramework section with code first -->
<!--<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />-->
</configSections>
<connectionStrings>
<add name="cf5WebContext" connectionString="Data Source=(local);Initial Catalog=cffb;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment