// How to define this here? as the class is not created by Microsoft Identity by default.
//public virtual AspNetUsers CreatedByEmployee { get; set; }
在 Asp.net Core Identity 中,该类映射到表,因此如果要配置外键,可以使用 IdentityUser 类,请检查以下代码:IdentityUserAspNetUsers
public class FileUserInfo
{
[Key]
public int FileUserInfoId { get; set; }
public string UserName { get; set; }
public string RecipientEmailAddress { get; set; }
public DateTime CreationDate { get; set; }
// This is my foreign key. // use the ForieignKey attribute to assign the foreign key.
[ForeignKey("CreatedByEmployee")]
public string CreatedByEmployeeId { get; set; }
public virtual IdentityUser CreatedByEmployee { get; set; }
}
在 DbContext 中添加 FileUserInfos
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<FileUserInfo> FileUserInfos { get; set; }
}
迁移后,结果如下:
有关使用 Asp.net Core Identity 的更多详细信息,请参阅 ASP.NET Core 上的 Identity 简介和 ASP.NET Core 中的 Identity 模型自定义。
由于该类继承了 ,在 Controller 中,可以注入 ,然后通过 访问表,然后就可以根据用户名找到当前用户,之后就可以得到用户 Id 值了。请参阅以下代码:ApplicationDbContextIdentityDbContextApplicationDbContextAspNetUserscontext.Users
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext _context;
public HomeController(ILogger<HomeController> logger, ApplicationDbContext applicationDbContext)
{
_logger = logger;
_context = applicationDbContext;
}
public IActionResult Index()
{
if (!string.IsNullOrEmpty(HttpContext.User.Identity.Name))
{
var user = _context.Users.Where(c => c.UserName == HttpContext.User.Identity.Name).FirstOrDefault();
//after getting the user, you can get the userid.
var userid = user.Id;
//or
var id = User.FindFirstValue(ClaimTypes.NameIdentifier);
var fileuser = new FileUserInfo() { CreatedByEmployee = user, UserName = "AA" };
_context.FileUserInfos.Add(fileuser);
_context.SaveChanges();
var result = _context.FileUserInfos.ToList();
}
return View();
}
如果答案有帮助,请点击“接受答案”并点赞。
注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知