如何传递 Class 的 Id 值?

How to Pass Id value of the Class?

我正在开发用户注册,它有另一个 class 字段。我的问题是我无法理解如何将 Guid id 传递给 class 字段。

为了清楚起见, 我有一个 IdentityUser 模型:

        public string Name { get; set; }

        public string MiddleName { get; set; }

        [Required]
        public string Surname { get; set; }

        public DateTime BirthDate { get; set; }

        public string Address { get; set; }

        [Required]
        public string UserType { get; set; }
        public bool ParentsAgreement { get; set; }

        public Section BelongSection { get; set; }

我有 Section 模型:

        [Required]
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string CoachName { get; set; }
        public string SportComplexTitle { get; set; }
        [IgnoreDataMember]
        public ICollection<User> UsersList { get; set; }

DbContext 方法是:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //section
            modelBuilder.Entity<User>()
                .HasOne(s => s.BelongSection)
                .WithMany(a => a.UsersList);

            modelBuilder.Entity<Section>()
                .HasMany(s => s.UsersList)
                .WithOne(a => a.BelongSection);
        }

我的注册方式是:

public async Task<AuthenticationResult> RegisterAsync(RegisterModel registerModel)
        {
            var existingUser = await _userManager.FindByNameAsync(registerModel.Username);

            if (existingUser != null)
            {
                return new AuthenticationResult
                {
                    Errors = new[] { "User with such username already exists" }
                };
            }
           
            var newUser = new User
            {
                Name = registerModel.Name,
                Surname = registerModel.Surname,
                BirthDate = registerModel.BirthDate,
                UserName = registerModel.Username,
                Email = registerModel.Email,
                PasswordHash = registerModel.PasswordHash,
                BelongSection = registerModel.BelongSection,
                UserType = registerModel.UserType
            };

            var createdUser = await _userManager.CreateAsync(newUser, registerModel.PasswordHash);
            

            if (!createdUser.Succeeded)
            {
                return new AuthenticationResult
                {
                    Errors = createdUser.Errors.Select(x => x.Description)
                };
            }

            return GenerateAuthenticationResultForUser(newUser);
        }

它的注册模型与用户模型相同,我将部分作为 class 传递。 下一步是我使用 Angular 进行 Web 开发,我在下拉列表中获取部分名称列表,并将该值作为每个部分的 ID 传递。 所以,我有一个带有 Section Basketball 的下拉列表,它的值 == guid id。 这就是为什么我将值 id 从 Angular 传递到服务器并且我得到“将类型 Guid 转换为值 Models.Section 时出错”。 我该如何处理?

如果我理解你的问题,你需要在创建新用户时创建一个 guid,但是如果你使用一个支持自动生成 guid 的数据库会更好。

1.没有 Guid 生成的数据库代码:

  var newUser = new User
        {
            Id = new Guid(),
            Name = registerModel.Name,
            Surname = registerModel.Surname,
            BirthDate = registerModel.BirthDate,
            UserName = registerModel.Username,
            Email = registerModel.Email,
            PasswordHash = registerModel.PasswordHash,
            BelongSection = registerModel.BelongSection,
            UserType = registerModel.UserType
        };

2。具有 Guid 生成的数据库代码: 在这里,您需要编辑 DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        //section
        modelBuilder.Entity<User>()
            .HasOne(s => s.BelongSection)
            .WithMany(a => a.UsersList)
            .ValueGeneratedOnAdd();

        modelBuilder.Entity<Section>()
            .HasMany(s => s.UsersList)
            .WithOne(a => a.BelongSection);
    }
        var newUser = new User
        { 
            BelongSection = registerModel.BelongSection, 
        };

the Registration model for it is the same as the User model, where I'm passing the Section as a class. Next step is that I use Angular for the web development and I'm getting the list of Section name in the dropdown list and passing the value as an id of each of them. So, I have a dropdown with Section Basketball and its value == guid id. That's why, I'm passing the value id from the Angular to the server and I'm getting the "Error converting type Guid to value Models.Section". How should I deal with that?

根据你的描述,好像注册用户的时候,你会使用DropDownlist列出Section,然后,将选择的section的Id值传递给服务器,然后插入新用户。如果是这种情况,在注册模型中,我建议您可以添加一个 Guid 属性 来存储所选部分的 Id 值,如下所示:

public class RegisterViewModel
{
    public string Name { get; set; }

    public string MiddleName { get; set; }

    [Required]
    public string Surname { get; set; }

    public DateTime BirthDate { get; set; }

    public string Address { get; set; }

    [Required]
    public string UserType { get; set; }
    public bool ParentsAgreement { get; set; }

    public Guid BelongSection { get; set; } //selected section
}

然后,在Register Post 方法中,您可以根据选择的section id 从数据库中找到现有的Section,然后将其分配给新用户。代码如下:

    public IActionResult Register()
    {
        //get section from database and use viewBag to bind dropdownlist.
        ViewBag.ListOfSection = _context.Sections.ToList();
        return View();
    }

    [HttpPost]
    public IActionResult Register(RegisterViewModel register)
    { 
        //find the seleted section from database.
        var selectedsection = _context.Sections.Where(c => c.Id == register.BelongSection).FirstOrDefault();
        //
        var newUser = new User
        {
            //...
            BelongSection = selectedsection,
        };

        //insert the new user into database.

        return View();
    }

截图是这样的: