将相关数据添加到身份

时间:2018-08-27 00:08:38

标签: asp.net entity-framework model-view-controller ef-code-first asp.net-identity

有大量使用IdentityUser界面的EF代码优先教程,但没有一个能说明如何向用户添加/更新相关数据。我正在使用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类,它创建消息表并在两个模型之间建立一对多关系。

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

这一切都很酷,但是我该如何为适当的用户添加新的消息条目?在阅读有关“类似”问题的教程时,我读到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); 

欢迎任何智慧。谢谢你们。

1 个答案:

答案 0 :(得分:0)

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

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

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

如果UserMan.FindAsyncByName返回IQueryable<AppUser>,则:

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

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