Search code examples
c#angularasp.net-coreforeign-keysregistration

How to Pass Id value of the Class?


I'm developing registration of the User, that has a field of another class. My issue is that I can't understand how to pass the Guid id to the class field.

To make it clear, I have an IdentityUser model:

        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; }

and I have the Section model:

        [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; }

The DbContext method is:

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);
        }

My registration method is:

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);
        }

and 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?


Solution

  •         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?

    According to your description, it seems that when register the user, you will list the Section using DropDownlist, then, pass the selected section's Id value to the server, then insert new user. If that is the case, in the Register Model, I suggest you could add a Guid property to store the selected section's Id value, Like this:

    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
    }
    

    Then, in the Register Post method, you could according to the selected section id to find the exiting Section from database, then, assign it to the new user. Code as below:

        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();
        }
    

    The screenshot like this:

    enter image description here