将相关数据添加到身份

Add Related data to Identity

有大量使用 IdentityUser 界面的 EF 代码优先教程,但 none 的内容是如何 add/update 向用户提供相关数据。我正在使用 ASP.NET MVC,所以假设我有以下用户模型

  public class AppUser : IdentityUser
  {
      public ICollection<Message> msges { get; set; }
  }

以及消息的模型

public class Message
{
    public string MessageId { get; set; }

    public string msg { get; set; }

    [DataType(DataType.Date)]
    public DateTime msgTime { get; set; }

    public string UserId { get; set; }
    public AppUser AppUser { get; set; }
}

当然 dbcontext class 创建消息 table 并在两个模型之间建立一对多关系。

public class AppIdentityDBContext : IdentityDbContext<AppUser>
{
    public AppIdentityDBContext() : base() 
    { }

    public AppIdentityDBContext(DbContextOptions<AppIdentityDBContext> options) : base(options) 
    { }

    public DbSet<Message> Messages { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<AppUser>()
                .HasMany(x => x.msges)
                .WithOne(y => y.AppUser);
    }
}

一切都很好,但我如何为适当的用户添加新的消息条目?阅读有 "similar" 个问题的教程,我读到 UserManager 个实例作业是更新用户数据。所以我在控制器中尝试了这样的事情:

 // Find the user, what works
 AppUser Benny = UserMan.FindAsyncByName("BennyHill");

 // I create a message object than I add it the Benny's msgs property
 Benny.msgs.Add(newMessage);   // --> for some reason this throws nullreference exception

 // Next step would be to update the data with the UserManager instance
 await UserMan.UpdateAsync(Benny); 

欢迎任何智慧。谢谢大家。

错误是由于实体中的集合默认为#null。 要添加到集合中,您应该首先预先加载集合。首先,将集合设置为虚拟集合会有所帮助,以便 EF 代理它并在必要时延迟加载。它有助于自动初始化集合成员以避免空引用,尤其是在“新建”实体时...

public class AppUser:IdentityUser
{
    public virtual ICollection<Message> msges { get; set; } = new List<Message>();
}

从这里开始,您的示例可能会起作用,因为您可以将新项目添加到 msges 集合中,但通常在使用集合时您会希望预先加载列表:

if UserMan.FindAsyncByName returns IQueryable<AppUser> 那么:

AppUser Benny= await UserMan.FindAsyncByName("BennyHill").Include(x => x.Msges);

否则,在 FindAsyncByName 中,您需要包含 .Include(x => x.Msges)