C# IdentityDbContext不从我的数据库初始值设定项调用种子方法

C# IdentityDbContext不从我的数据库初始值设定项调用种子方法,c#,entity-framework,autofac,asp.net-identity-2,C#,Entity Framework,Autofac,Asp.net Identity 2,我正在尝试使用Entity Framework、Autofac和Identity 2.0将初始用户设置为管理员角色 下面是我的应用程序上下文类: public class ApplicationContext<TUser> : IdentityDbContext<TUser> where TUser : IdentityUser { public ApplicationContext(string conectionString) : base(conection

我正在尝试使用Entity Framework、Autofac和Identity 2.0将初始用户设置为管理员角色 下面是我的应用程序上下文类:

public class ApplicationContext<TUser> : IdentityDbContext<TUser> where TUser : IdentityUser
{
    public ApplicationContext(string conectionString) : base(conectionString) 
    { 
        Database.SetInitializer(new MyContextInitializer()); 
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //entities builder and configuration
    }
}
和我的自定义初始值设定项:

class MyContextInitializer : DropCreateDatabaseIfModelChanges<ApplicationContext<IdentityUser>>
{
    protected override void Seed(ApplicationContext<IdentityUser> context)
    {
        //seeding data
    }
}

问题是从未调用seed方法。发生了什么,如何解决?谢谢你的进步

根据我的理解,在创建任何实例(包括构造函数中的实例)之前,必须调用Database.SetInitializer

一种方法是使用静态构造函数:

public class ApplicationContext : IdentityDbContext<TUser> 
  where TUser : IdentityUser
{
  static ApplicationContext()
  { 
    Database.SetInitializer<ApplicationContext>(new MyContextInitializer()); 
  }
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    //entities builder and configuration
  }
}

抢手货这就是我的位置。@SteveGreene Idk为什么,但当我从ApplicationContext类中删除类型时,问题就消失了。也许是这样,但静态构造函数或Global.asax是一个更好的位置,或者每次构造实例时都会运行该代码。我不喜欢Global.asax中的代码,类应该是自给自足的。否则,使用相同上下文的任何其他人将从同一类中获得不同的结果。@SteveGreene谢谢。但您需要删除公共修饰符和泛型类型。我认为如果在应用程序上下文中保留泛型是不可能的——ApplicationContext不能隐式地转换为ApplicationContext。您可能可以向MyContextInitializer添加泛型参数,并使用TUser作为其种子方法-但现在无法检查。@raderick感谢您的回复,但我已从上下文中删除泛型类型,一切正常!