ASP.NET добавить список в ApplicationUser

Я хочу добавить список объектов 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 равно нулю).

Что случилось?


person jcmag    schedule 20.03.2016    source источник


Ответы (1)


FindById не будет возвращать вашу пользовательскую дочернюю коллекцию по умолчанию. Вы можете получить доступ к таблице Users напрямую:

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

Лучшим способом было бы реализовать свой собственный UserStore, который переопределяет FindById, подобный этому: many">Пользовательские объекты с идентификацией сети asp (один ко многим)

person Steve Greene    schedule 21.03.2016