我試圖讓實體框架代碼首先爲我創建一個數據庫,但似乎遇到了問題與它沒有實際創建表。獲取實體框架來生成我的表
在我的web.config我有連接字符串設置,並指出數據庫(不含表)我設置:
<connectionStrings>
<add name="DataContext" connectionString="Server=.\SQLEXPRESS;Database=MyDatabase;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>
在我DataConext.cs位於我的域的項目,我有以下類: (我用的Altairis.Web.Security插件,以幫助會員的東西)
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));
}
}
在我的Web項目的Global.asax.cs我:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer(new DataContextInitializer());
}
一切都編譯和工作,但數據庫表永遠不會爲我生成。從網上閱讀,我認爲這可能是Database.SetInitializer,但我不確定它應該調整到什麼程度?
任何幫助指向我在正確的方向將是偉大的!我有這個工作我家裏的電腦上運行,但在另一臺PC上這個項目只是工作不因某種原因 - 典型;)
感謝, 豐富
檢查此答案:http://stackoverflow.com/questions/6662491/cannot-generate-database-from-entity-framework-4-1-codefirst-with-sql-server-2005/6662746#6662746 –