What is the proper method for storing user registration information in the database so that it can be easily retrieved and accessed later? (Error message)

User.cs: An error is occurring in the User class where 'User' is not a valid type in the context of TestBlazor project. It happened when attempting to save user registration data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestBlazor.Models;

namespace TestBlazor.Data
{
    public class Users
    {
        public static void AddUsers()
        {
            using (var context = new AppDbContext())
            {
                //var user = new User { Url = "" }; //what this?
                context.User.Add(User); //this error
                context.SaveChanges();
            }
        }
    }
}

The Model is linked to an empty table in the database. AppDbContext.cs:

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestBlazor.Models;

namespace TestBlazor.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext()
        {

        }

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
            }
        }

        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{
        //    base.OnModelCreating(modelBuilder);
        //    modelBuilder.Entity<User>()
        //}

        public DbSet<User> User { get; set; }
        public DbSet<Item> Items { get; set; }


    }

}

The User Model: User.cs

 [Table("Users")]
    public class User
    {
        [Display(AutoGenerateField = false)]
        public int UserId { get; set; }

        [Display(Name = "UserName")]
        [Required(ErrorMessage = "UserName is required.")]
        public string UserName { get; set; }

        [Display(Name = "Password")]
        [Required]
        [MinLength(8, ErrorMessage = "password must be atleast 8 characters")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Email")]
        [Required(ErrorMessage = "Email is required.")]
        public string Email { get; set; }

        [Display(Name = "Company")]
        [StringLength(255)]
        [Required(ErrorMessage = "Company is required.")]
        [Remote("doesCompanyExist", "Company", HttpMethod = "POST", ErrorMessage = "Company already exists. Please enter a different company.")]
        public string Company { get; set; }

        public User GetRegisteredUser()
        {
            return new User
            {
                UserName = UserName,
                Password = Password,
                Email = Email,
                Company = Company,

            };
        }

    }

Registration layout: Register.razor:

@page "/register"

@using TestBlazor.Models

<br />
<br />

<h3><b>Register</b></h3>
<br />

<EditForm class="needs-validation" Model="@_user" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
    <div class="alert @StatusClass">@StatusMessage</div>
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="form-group">
        <p><b>User name</b></p>
        <input id="username" class="solid" name="username" placeholder="Your username.." @bind-value="_user.UserName" />
        <ValidationMessage For="@(() => @_user.UserName)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p><b>Password</b></p>
        <input type="password" class="solid" id="password" placeholder="Your password.." @bind-value="_user.Password" />
        <ValidationMessage For="@(() => @_user.Password)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p><b>Email</b></p>
        <input id="email" class="solid" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1861776d587d60797568747d367b7775">[email protected]</a>" @bind-value="_user.Email" />
        <ValidationMessage For="@(() => @_user.Email)"></ValidationMessage>
    </div>
    <div class="form-group">
        <p><b>Company</b></p>
        <input id="company" class="solid" placeholder="Your company.." @bind-value="_user.Company" />
        <ValidationMessage For="@(() => @_user.Company)"></ValidationMessage>
    </div>


    <br />

    <button disabled="@loading" class="btn btn-primary">

        @if (loading)
        {
            <span class="spinner-border spinner-border-sm mr-1"></span>
            <NavLink href="/login" class="btn btn-link">Register</NavLink>
        }
        Register
    </button>
    <NavLink href="/login" class="btn btn-link">Login</NavLink>
</EditForm>



@code {
    private User _user = new User();

    private string StatusMessage;
    private string StatusClass;

    private bool loading;


    private void OnValidSubmit()
    {
        if (loading == true)
        {
            Console.WriteLine("You have successfully registered!");
        }

        else
        {
            loading = false;
            Console.WriteLine("Check your information again!");
        }
    }

    protected void HandleValidSubmit()
    {
        StatusClass = "alert-info";
        StatusMessage = " You have successfully registered! Please click the Login button to log in!";
    }

    protected void HandleInvalidSubmit()
    {
        StatusClass = "alert-danger";
        StatusMessage = " Check your information again!";
    }


    public bool doesCompanyExist(string Company)
    {
        try
        {

            if (Company != null)
            {
                return true;
            }

        }
        catch (Exception)
        {
            return false;
        }

        return false;

    }

}

Answer №1

It seems like the issue lies in attempting to add a class called User to the User table using entity framework. To resolve this, uncomment the line

//var user = new User { Url = "" }; //what this?
and update the line context.User.Add(User); by passing user instead. Here is an example:

using (var context = new AppDbContext())
{
    var user = new User { Url = "" };
    context.User.Add(user);
    context.SaveChanges();
}

I didn't delve into your other code, but it is important to ensure that proper initialization of the User instance takes place before adding it to the table.

Edit: It appears that Url may not be a property of User, so make sure to properly initialize the User object before using the .Add() method with entity framework.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hide jQuery dropdown when mouse moves away

I am working on designing a navigation bar with dropdown functionality. Is there a way to hide the dropdown menu when the mouse pointer leaves both the navbar menu and the dropdown itself? I have tried using hover, mouseenter, and mouseleave but due to my ...

Repetitive creation of unnecessary classes

I am currently in the process of developing an automation framework using C# and SpecFlow. One issue that I am facing is the frequent instantiation of a class to access methods or web elements. Here is a snippet of the class that I instantiate in a separa ...

"Vertical Line Encoding: A Strategy for Improved Data

Can someone help me with a coding issue I'm facing on my website? I am trying to create three vertical lines to separate images in columns, but every time I exit the editor and preview the site, the position of the lines changes. I'm new to HTML ...

Updating CSS class within a div tag utilizing ASP.NET (C#)

How can I dynamically update the properties of a CSS class using C#? I need to change the background image, font size, font style, and font based on user input through an interface. Once the changes are saved, I store them in a database. However, when the ...

Avoiding ChartJS tooltips from being cut off

I've been exploring how to prevent chartjs from cutting off its tooltips, but I haven't been able to find a config option to address this issue. https://i.sstatic.net/Knzvd.png Here's what I've attempted so far: <script> ...

What is the best way to design an element that exceeds the size of my physical body

I am currently working on creating a table that needs to be larger than the body and centered. Let me provide some more information. Below is my simplified HTML code : <body> <div id="one"> <div> <tab ...

Decide on the chosen option within the select tag

Is there a way to pre-select an option in a combobox and have the ability to change the selection using TypeScript? I only have two options: "yes" or "no", and I would like to determine which one is selected by default. EDIT : This combobox is for allow ...

Is there a way to delete content in HTML after a particular text using Python and BeautifulSoup4?

I am currently in the process of scraping information from Wikipedia. My goal is to extract only the necessary data and filter out any irrelevant content such as See also, References, etc. <h2> <span class="mw-headline" id="See ...

Django experiencing issue of "Unable to locate view" even though the view is clearly defined

Having an issue with the django 4.0.4 framework, I am seeing the error message "Reverse for 'upload' not found. 'upload' is not a valid view function or pattern name". The strange thing is that it was working fine earlier today, and I&a ...

Best placement for <img> tag in HTML for creating a background image using CSS (excluding CSS3)

I am currently working on a programming project called Broadway through Codeacademy. I have been given the task of adding a background image to the webpage. It seems like an easy task to accomplish. The simplest way to achieve this effect is by using the f ...

What is the purpose of the hidden tag that accompanies a checkbox?

Similar Question: ASP.NET MVC: Why is Html.CheckBox generating an extra hidden input? While working on an asp.net mvc project, I noticed that when rendering a checkbox control, it also generates an additional hidden field like the examples below: < ...

What makes it possible for Vue v3 to handle variables that are undefined?

We are in the process of developing a web application that monitors analytical changes and updates them in real time. While this may not be crucial information, we thought it would be worth mentioning. If you visit Vue.js's official website at https: ...

What is the best way to show the response data in an input text field within an HTML form?

I'm new to working with node.js and I've encountered an issue. I need to display the data of the currently logged in user in input fields. With the following code, I can access the data of the logged-in user and display it on the console: See O ...

When it comes to carousel dynamic items, I encounter an issue when using the splice function to remove an item

When using the splice function to delete an item (image), all the images are being deleted. When I delete an item, I want the carousel to show the remaining images instead of disappearing. <div id="carouselExampleControls" class="carousel slide" data ...

Is it possible to incorporate a LINK within the CSS GRID layout?

Hey everyone, I've encountered an issue with my link placement in the grid. I'm looking to turn the entire box into a clickable link. * { padding: 0; margin: 0; } body { font-family: Hiragino Kaku Gothic Pro W3, Arial; } .title-conta ...

The minimum height of the IE element could not fully expand within its flex container that was set to absolute positioning

Creating a webpage with a full-page layout using a content session that spans the entire height of its container is my current project. To achieve this, I have implemented the following: The content's container (div.inner) is set to be absolute-posi ...

Show a specific item when selecting an option from a dropdown menu

Hey there, I have a question regarding creating a theme for the Genesis Framework. Right now, I'm facing a challenge with one particular element. Here's the situation: I've got two drop-down lists, but I only want the second one to be visib ...

Can Selenium be used to retrieve a list of pinned IDs from a website?

I am currently developing a web scraper that is required to open multiple tabs of items with filled icons. Specifically, each page that needs to be opened contains the div class="course-selector-item-pinned" in its source code. <dropdown-conte ...

Searching for a single cell within an HTML table

I've been on the hunt for a code that can search through a table and show just one cell. I tried creating my own, but finally stumbled upon one that seems to work perfectly, except for one hiccup. When the search bar is cleared, it displays the first ...

PHP Form Functions Properly on Firefox, but Encounters Issues on IE and Chrome

I'm having an issue with a form I created to send to my email. The form works fine in Firefox, but it's not functioning properly in Chrome or Internet Explorer. Any assistance would be greatly appreciated! EDIT The problem is that the php code i ...