【问题标题】:Seeding a membership user throws null reference exception播种会员用户会引发空引用异常
【发布时间】:2014-03-17 13:33:57
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    知道了,我错过了在使用前初始化 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");
    

    ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2013-05-06
      相关资源
      最近更新 更多