简体   繁体   English

ASP.NET MVC 4模板:播种数据(实体框架)

[英]ASP.NET MVC 4 Template: Seeding data (Entity Framework)

I am using ASP.NET MVC 4 Internet application template. 我正在使用ASP.NET MVC 4 Internet应用程序模板。 I have successfully added some custom tables to the existing database that is created automatically but now I want to seed some data to one of my tables once database is created. 我已经成功将一些自定义表添加到了自动创建的现有数据库中,但是现在我想在创建数据库后将一些数据播种到我的一个表中。 I know I can do it by overriding the Seed method on the database initializer but as by default asp.net mvc4 sets the initializar to null I am not sure if I change the initializer can cause some new issues or side effects... how to do it? 我知道我可以通过重写数据库初始化程序上的Seed方法来做到这一点,但是默认情况下,asp.net mvc4将Initializar设置为null我不确定是否更改初始化程序会导致一些新问题或副作用...如何会吗

// I could implement this custom initializer but as by default is set to null
// 
public class UsersContextSeedInitializer : CreateDatabaseIfNotExists<UsersContext>
{
    protected override void Seed(UsersContext context)
    {
       // Populate my table here
    }
}

    private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            Database.SetInitializer<UsersContext>(null);

            // I could do it here or better below?: Database.SetInitializer(new UsersContextSeedInitializer());


            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

            // better here?: Database.SetInitializer(new UsersContextSeedInitializer());

                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }
    }

You should call the database initializer from your Global.asax as it needs to be called before the first use of the DbContext. 您应该从Global.asax调用数据库初始化程序,因为在首次使用DbContext之前需要调用它。

In John Papa's pluralsight course on SPA, the implementation he has is as follows, this is in his derived DbContext Class (note the comment): 在John Papa的SPA复数课程中,他的实现如下,这是在他派生的DbContext类中(请注意注释):

// ToDo: Move Initializer to Global.asax; don't want dependence on SampleData
static CodeCamperDbContext()
{
    Database.SetInitializer(new CodeCamperDatabaseInitializer());
}

This question also supports this. 这个问题也支持这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM