首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为IdentityUser添加外键,创建用户时提示主表外键冲突?

为IdentityUser添加外键,创建用户时提示主表外键冲突?

提问于 2023-09-20 16:24:55
回答 1关注 0查看 114
代码语言:js
复制
[NotMapped]
public class AppUser:IdentityUser
{
    [Required]
    public string RealName { get; set; } = default!;

    [Required]
    [ForeignKey("DepartmentId")]
    public Department Department { get; set; } = default!;
}

    public class Department
    {
        [Key]
        public int DepartmentId { get; set; }

        [Required]
        public string Name { get; set; } = default!;

        public Department? Parent { get; set; }
    }

IdentityUser扩展了Department外键,在增加用户时,提示外键冲突,怎么解决?

代码语言:js
复制
if (ModelState.IsValid)
{
    var user = new AppUser { UserName = model.UserName, RealName = model.RealName};
    var dep = _departmentRepository.Departments.FirstOrDefault(d => d.DepartmentId == Id);
    user.Department = dep;
    
    if (model.Password != null)
    {
        var result = await userManager.CreateAsync(user, model.Password);
    }
    return View(model);
 }

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档