ASP.NET将列表添加到ApplicationUser

时间:2016-03-20 22:36:54

标签: c# asp.net ef-code-first entity-framework-6

我想在MyActivity应用中创建的标准ApplicationUser对象中添加ASP.NET webforms对象列表:

public class ApplicationUser : IdentityUser
{
    public ICollection<MyActivity> Activities { get; set; } // Added that

    public ClaimsIdentity GenerateUserIdentity(ApplicationUserManager manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    public Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
    {
        return Task.FromResult(GenerateUserIdentity(manager));
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

我将MyActivity类定义为:

public class MyActivity
{
    public Guid Id { get; set; }
    public ApplicationUser User { get; set; }
    public string SomeProp { get; set; }
}

然后我执行了#34; add-migration UserActivities&#34;和&#34; update-database&#34;。我创建了一个MyActivities表,其中包含一个User_Id外键,引用了AspNetUsers.Id。 一切都很好。

但现在,当我尝试添加活动时:

using (var db = new ApplicationDbContext())
{
    var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var currentUser = manager.FindById(User.Identity.GetUserId());
    currentUser.Activities.Add(new MyActivity { SomeProp = "1" });
    db.SaveChanges();
}

我得到NullReferenceExceptioncurrentUser.Activities为空)。

有什么问题?

1 个答案:

答案 0 :(得分:0)

FindById默认不会返回您的自定义子集合。您可以直接访问Users表:

var currentUser = db.Users.Include(u => u.Activities).First(u => u.Id == manager.FindById(User.Identity.GetUserId());

更好的方法是实现自己的UserStore,覆盖类似于此的FindById:Custom entities with asp net identity (one-to-many)