首页 > 解决方案 > ASP.NET Core 3.0 将身份用户分配给自定义模型

问题描述

假设我有模型 Post.cs 并且您想添加创建此帖子的用户。我想我可以直接使用身份用户并将他们附加到帖子,或者可能只是他们的 ID。我不想扩展它,只是将它分配给帖子。这是我的自定义模型:

 public class Post
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public string UserId { get; set; }

    public User User { get; set; }

    public DateTime DateCreated { get; set; }

    public DateTime? DateUpdated { get; set; }

    public DateTime DateDeleted { get; set; }

    public bool Deleted { get; set; }

    public bool Approved { get; set; }
}

第四行和第五行是我要分配给帖子的 APS.NET 默认身份用户数据

标签: c#asp.netasp.net-core

解决方案


我不确定你的问题到底是什么。如果您尝试创建一对多关系,请参阅这个简单的示例。

public class Post
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Content { get; set; }

    public string UserId { get; set; }

    public User User { get; set; }


}

public class User : IdentityUser
{
    public virtual ICollection<Post> Posts { get; set; }
}

这将在用户和帖子之间创建一对多的关系。帖子有一个用户,但用户可以有多个帖子。这样,您还扩展了 IdentityUser。


推荐阅读