数据库初始化策略Code First

时间:2013-05-14 11:46:50

标签: database asp.net-mvc-4 ef-code-first

我有一个ASP.NET-MVC应用程序,启用了MigrationSimpleMemberShipProvider配置为使用我的数据库和一些额外的表/字段。

我的问题是,我的数据库初始化在哪里?因为我还在开发它,我可以删除数据库/表和数据并重新创建它。

我已将它放在configuration.cs文件中,但我不确定这是否是数据库初始化程序的位置。

namespace CFContext.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using WebMatrix.WebData;
    using System.Web.Security;
    using System.Collections.Generic;

internal sealed class Configuration : DbMigrationsConfiguration<DataContext>
{
    public Configuration()
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());
        //Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataContext>());
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(DataContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //

        SeedMembership(context);
    }

    private void SeedMembership(DataContext context)
    {
        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

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

        if (!roles.RoleExists("Administrator"))
            roles.CreateRole("Administrator");

        if (membership.GetUser("Username0", false) == null)
        {

        }
      }
    }
}

3 个答案:

答案 0 :(得分:6)

public class ContextInitializer : CreateDatabaseIfNotExists<Context>
{     
    private static void InitializeWebSecurity()
    {
        if (WebSecurity.Initialized)
            return;

        WebSecurity.InitializeDatabaseConnection(
            connectionStringName: "DefaultConnection",
            userTableName: "User",
            userIdColumn: "Id",
            userNameColumn: "Email",
            autoCreateTables: true);

        Roles.CreateRole("Admin");
        Roles.CreateRole("Customer");
    }       

    protected override void Seed(Context context)
    {
        InitializeWebSecurity();

        // more seeding
        context.SaveChanges();
    }
}

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AuthConfig.RegisterAuth();
        DatabaseConfig.RegisterDatabase();
        AutoMapperConfig.RegisterConfig();

        // Set the initializer here
        Database.SetInitializer(new ContextInitializer());

        // Now initialize it
        using (var context = new Context())
        {
            context.Database.Initialize(false);
        }

        // Double check seeding has initalized, if not
        // We initialize it here to make sure.
        if (!WebSecurity.Initialized)
        {
            WebSecurity.InitializeDatabaseConnection(
                connectionStringName: "DefaultConnection", 
                userTableName: "User", 
                userIdColumn: "Id", 
                userNameColumn: "Email", 
                autoCreateTables: false);
        }
    }
}

您应该可以使用此设置以相同的方式创建迁移。

答案 1 :(得分:5)

将您的数据库初始化代码放入 Global.asax

中的“ Application_Start ”方法

答案 2 :(得分:0)

我把它放在Global.asax.cs的Application_Start中

protected void Application_Start()
        {
            WebSecurity.InitializeDatabaseConnection("Name of Connection String", "User Table in DataBase", "UserId Column", "UserName Column", true);
        }

这是真的,意味着我想自动创建表格。

在Web.config文件中,您需要设置提供程序:

<system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />

    <membership defaultProvider="nameProvider">
      <providers>
        <add name="nameProvider" type="WebMatrix.WebData.SimpleMembershipProvider,WebMatrix.WebData" />
      </providers>
    </membership>
  </system.web>

它对我有用。