2016-03-20 4 views
0

Я хочу, чтобы добавить список MyActivity объекта к стандартному ApplicationUser объекта, созданного в ASP.NET webforms приложении:ASP.NET добавить список ApplicationUser

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; } 
} 

Затем я выполнил «add-migration UserActivities» и «update-database». У меня есть таблица 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

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

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)

Смежные вопросы