Я хочу добавить список объектов 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; }
}
Затем я выполнил «добавление миграции UserActivities» и «обновление базы данных». У меня создана таблица 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
равно нулю).
Что случилось?