实体框架SetInitializer和种子数据

时间:2014-12-08 17:09:52

标签: entity-framework-6

难以弄清楚为什么我的数据库不会播种:

以下是我在Global.asax代码中的内容:

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();

        Database.SetInitializer(new DataContextInitializer());
        DataContext db = new DataContext();
        db.Database.Initialize(true);

        WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);

    }

,这是DataContextInitializer:

public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
 {
    protected override void Seed(DataContext context)
    {
        if (!WebSecurity.Initialized)
        {
            WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);
            WebSecurity.CreateUserAndAccount("admin", "12345");
        }

        var roles = (SimpleRoleProvider)Roles.Provider;
        var membership = (SimpleMembershipProvider)Membership.Provider;

        if (!roles.RoleExists("admin"))
        {
            roles.CreateRole("admin");
        }
        if (membership.GetUser("admin", false) == null)
        {
            membership.CreateUserAndAccount("admin", "12345");
        }
        if (!roles.GetRolesForUser("admin").Contains("admin"))
        {
            roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" });
        }
    }
}

在调试时,我得到的SqlException是&#34;在数据库中已经有一个名为...的对象。&#34;知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

这是我采取的步骤:

  • 将种子逻辑复制到Migrations Configuration.cs文件。
  • 从项目中排除旧迁移
  • 在包控制台管理器中执行了添加迁移并为其命名
  • 然后运行update-database -verbose -force确保WebMatrix.WebData引用属性具有&#39; CopyLocal = true&#39;

我希望这有助于某人。