Asp.Net IdentityUser 添加自定义列表 属性

Asp.Net IdentityUser add custom List Property

我对使用 asp.net 进行编码还很陌生,所以我的问题可能有明显的答案,但我还没有找到答案。

所以目前我正在开发一个项目管理网站,我希望用户在事件发生时得到通知,例如。他们被添加到一个新项目,一个项目已经更新等

为此,我用新的 属性 列表

扩展了 IdentityUser 模型
    public class CojectUser : IdentityUser
    {
        public List<Notification> Notifications { get; set; }
    }

    public class Notification
    {
        public int NotificationID { get; set; }
        public string Message { get; set; }
        public bool Seen { get; set; }
    }

当事件发生时,我将它们添加到用户的通知列表并通过 userManager 更新用户。

public class EventBroker<T> : IEventBroker<T>
    {
        private readonly UserManager<CojectUser> userManager;

        public EventBroker(UserManager<CojectUser> userMgr, IUserValidator<CojectUser> userValid)
        {
            userManager = userMgr;
        }

        public async Task NotifyAsync(Message<T> message, List<UserRole> recipients)
        {
            foreach (var user in recipients)
            {
                var cojectUser = await userManager.FindByNameAsync(user.Name);
                if (cojectUser != null)
                {
                    if (cojectUser.Notifications == null)
                    {
                        cojectUser.Notifications = new List<Notification>();
                    }
                    cojectUser.Notifications.Add(new Notification
                    {
                        Message = message.Information,
                        Seen = false
                    });
                    IdentityResult result = await userManager.UpdateAsync(cojectUser);
                    if (!result.Succeeded)
                    {
                        throw new UserUpdateFailException();
                    }
                }
            }
        }
    }
}

我可以将自定义数据保存到数据库中,但无法从数据库中再次加载它。 当我想显示用户的通知时,userManager 检索一个带有 null 的用户对象作为通知列表。即使数据存储在数据库中。

 public async Task<IActionResult> Index()
        {
            CojectUser user = await userManager.GetUserAsync(User);
            if(user.Notifications == null)
            {
                user.Notifications = new List<Notification>();
            }
            return View(user);
        }

数据库中的数据:

谁能告诉我我做错了什么?

UserManager 默认不预先加载属性。

您应该直接使用 DatabaseContext。

var user = _context.Users.Include(c => c.Notifications).Where(u => u.Id == user.Id).ToList();