为成员资格用户播种会引发空引用异常

时间:2014-03-17 13:33:58

标签: entity-framework asp.net-membership asp.net-mvc-5 seeding

使用MVC5和EF6我试图通过从AccountController Register Action复制代码来创建虚拟用户帐户,如下所示:

class SampleData : DropCreateDatabaseAlways<EFDbContext>
{
 public Microsoft.AspNet.Identity.UserManager<ApplicationUser> UserManager { get; private set; }

protected override void Seed(EFDbContext context)
    {

        base.Seed(context);
        var user = new ApplicationUser() { UserName = "Candidate1", AboutSelf = "", FirstName = "Candidate1",LastName="Candidate1",Sex=SexType.Unspecified,Id= Guid.NewGuid().ToString() };
         UserManager.CreateAsync(user, "Candidate1");
...

在上面的代码中添加了很少的自定义配置文件属性,我已经填充了所有,但我仍然得到空引用异常:

at TestPro.WebUI.SampleData.Seed(EFDbContext context) in d:\Users\Arvind\Documents\Visual Studio 2013\Projects\TestPro\TestPro.WebUI\Models\SampleData.cs:line 22
at System.Data.Entity.DropCreateDatabaseAlways`1.InitializeDatabase(TContext context)
at System.Data.Entity.Internal.InternalContext.<>c__DisplayClasse`1.<CreateInitializationAction>b__d()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Database.Initialize(Boolean force)
at TestPro.WebUI.MvcApplication.Application_Start() in d:\Users\Arvind\Documents\Visual Studio 2013\Projects\TestPro\TestPro.WebUI\Global.asax.cs:line 17

1 个答案:

答案 0 :(得分:0)

知道了,我错过了在使用前初始化UserManager属性

class SampleData : DropCreateDatabaseAlways<EFDbContext>
{
public Microsoft.AspNet.Identity.UserManager<ApplicationUser> UserManager { get; private set; }

protected override void Seed(EFDbContext context)
{
//Need to initialize UserManager property
UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    base.Seed(context);
    var user = new ApplicationUser() { UserName = "Candidate1", AboutSelf = "", FirstName = "Candidate1",LastName="Candidate1",Sex=SexType.Unspecified,Id= Guid.NewGuid().ToString() };
     UserManager.CreateAsync(user, "Candidate1");

...