I’m trying to get Entity Framework Code First to create a database for me but seem to be running into issues with it not actually creating the tables.
In my Web.Config I have the connection string setup and pointed to the database (without tables) I setup:
<connectionStrings>
<add name="DataContext" connectionString="Server=.\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>
In my DataConext.cs class located in my Domain project I have the following: (I am using the Altairis.Web.Security plugin to help with membership stuff)
public class DataContext : DbContext
{
public DbSet<Faq> Faqs { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Maps to the expected many-to-many join table name for roles to users.
modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(m =>
{
m.ToTable("RoleMemberships");
m.MapLeftKey("UserName");
m.MapRightKey("RoleName");
});
}
}
public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
{
protected override void Seed(DataContext context)
{
// create roles
var roles = new List<Role>{
new Role{RoleName = "Administrator"}, // admin area: admin user
new Role{RoleName = "User"}, // admin area: normal user
new Role{RoleName = "Client"} // front end: normal user
};
roles.ForEach(r => context.Roles.Add(r));
}
}
In my Web project Global.asax.cs I have:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new DataContextInitializer());
}
Everything compiles and works away but the database tables are never generated for me. From reading around online I think that this could be down to Database.SetInitializer but I’m not really sure what it should be adjusted to?
Any help to point me in the right direction would be great! I had this working on my home computer but running this project on another PC just isn’t working for some reason – typical 😉
Thanks,
Rich
Ok, got this working finally. Thanks to Ladislav Mrnka for the link I altered my global.asax to be:
i also adjusted my DataContextInitializer using BumbleB2na’s suggestion. The finished class looks like this:
It now works perfectly if I leave Entity Framework create the database for me and not Create one myself before running the code. Hopefully this helps someone else!