我想在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();
}
我得到NullReferenceException
(currentUser.Activities
为空)。
有什么问题?
答案 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)