asp.net-mvc – 如何使用Entity Framework和Membership表初始化数据库

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何使用Entity Framework和Membership表初始化数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用实体框架5.0代码优先的MVC4 Web应用程序。

在Global.asax.cs中,我有一个引导程序,初始化Entity.Database,强制数据库被初始化并初始化成员资格的数据库代码是这样的:

  1. System.Data.Entity.Database.SetInitializer(new DatabaseContextInitializer());
  2. Database.Initialize(true);
  3. WebSecurity.InitializeDatabaseConnection(DEFAULTCONNECTION,"UserProfile","UserId","UserName",autoCreateTables: true);

DatabaseContextInitializer目前很简单:

  1. public class DatabaseContextInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext>
  2. {
  3. protected override void Seed(DatabaseContext dbContext)
  4. {
  5. base.Seed(dbContext);
  6. db.Set<Workout>().Add(new Workout {Id = 1,Name = "My First workout user1"})
  7.  
  8. }
  9. }

问题是我无法创建用户到成员资格:

  1. WebSecurity.InitializeDatabaseConnection(DEFAULTCONNECTION,autoCreateTables: true);

因为我有一个问题,数据库没有创建。如何使用Entity Framework 5.0和Asp.Net MVC 4为数据库初始化一些默认用户

解决方法

请查看 following article的推荐方法,使​​用迁移种植您的数据库

这里是步骤:

>使用Internet模板创建一个新的ASP.NET MVC 4应用程序
>在您的包管理器控制台中键入以下命令:

  1. enable-migrations

>这将创建一个〜/ Migrations / Configuration.cs文件,您可以在其中种子您的数据库

  1. using System.Data.Entity.Migrations;
  2. using System.Linq;
  3. using System.Web.Security;
  4. using WebMatrix.WebData;
  5.  
  6. internal sealed class Configuration : DbMigrationsConfiguration<MvcApplication1.Models.UsersContext>
  7. {
  8. public Configuration()
  9. {
  10. AutomaticMigrationsEnabled = true;
  11. }
  12.  
  13. protected override void Seed(MvcApplication1.Models.UsersContext context)
  14. {
  15. WebSecurity.InitializeDatabaseConnection("DefaultConnection",autoCreateTables: true);
  16.  
  17. if (!Roles.RoleExists("Administrator"))
  18. {
  19. Roles.CreateRole("Administrator");
  20. }
  21.  
  22. if (!WebSecurity.UserExists("john"))
  23. {
  24. WebSecurity.CreateUserAndAccount("john","secret");
  25. }
  26.  
  27. if (!Roles.GetRolesForUser("john").Contains("Administrator"))
  28. {
  29. Roles.AddUsersToRoles(new[] { "john" },new[] { "Administrator" });
  30. }
  31. }
  32. }

>在web.config中指定memebership和角色提供程序:

  1. <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
  2. <providers>
  3. <clear/>
  4. <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider,WebMatrix.WebData"/>
  5. </providers>
  6. </roleManager>
  7. <membership defaultProvider="SimpleMembershipProvider">
  8. <providers>
  9. <clear/>
  10. <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider,WebMatrix.WebData" />
  11. </providers>
  12. </membership>

>在包管理器控制台中运行迁移:

  1. update-database -verbose

猜你在找的asp.Net相关文章