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

Troubleshooting Vue.js rendering problems on Safari_BROWSER

I'm encountering a strange issue with my portfolio website, which is built using Vue and Laravel. The problem arises specifically in Safari - the project thumbnails don't display until the browser window is resized. Here's the relevant code ...

Ajax successful event fails to trigger

Having Trouble Implementing Okta Authentication with WebForms The login functionality is working, but the redirect part is not functioning correctly I have attempted to use void and return a JSON object/string, but it does not seem to work If I remove th ...

Expanded MUI collapsible table squeezed into a single cell

I'm experimenting with using the MUI table along with Collapse to expand and collapse rows. However, I've noticed that when utilizing collapse, the expanded rows get squished into one cell. How can I adjust the alignment of the cells within the p ...

One-of-a-kind Version: "Utilizing CSS to Capitalize an

Imagine having the following strings. i and we. me and you. he and she. Is it possible to achieve the desired result using PURE CSS? I and We. Me and You. He and She. If capitalizing the text using text-transform: capitalize is used, it will yi ...

Angular 2: Implementing a Universal CSS Style Sheet

Is there a way to include a universal CSS file in Angular 2 applications? Currently, I have multiple components that share the same button styling, but each component has its own CSS file containing the styles. This setup makes it difficult to make changes ...

JavaScript - A simple way to retrieve the dimensions of an image consistently

I'm currently working on a piece of Jquery code that is designed to display an image fitting within the screen's dimensions. These images are generated dynamically as needed. However, I am facing an issue where the height and width of the image a ...

The Stripe card element seems to be missing from the form

I'm a newcomer to angularjs and currently working on integrating version 3 of the stripe api into my angular application. I followed the steps provided on the stripe website, but faced an issue when trying to incorporate their code which is primarily ...

Tips for Implementing Multi-Level/Nested in Ajax Requests

I am currently developing a user-friendly web application with intuitive multi-level options that loads new content without the need to refresh the entire page. This is how my structure looks: /index.php /schools.html /colleges.html Within schools.html, ...

Displaying iFrame Border in React Native WebView

When attempting to dynamically add YouTube videos to my React Native app, I decided to utilize a combination of WebView and iFrame due to the incompatibility of the current react-native-youtube component with RN 16+. Although this solution works, the ifram ...

Alter the div's HTML content once the Ajax operation is completed

I have a div element that looks like this: <div class="progress" id="progress-bar"></div> I am using the following JavaScript code along with an ajax call to retrieve some data. The data returned is 0, however, the content is not being added ...

Send properties to the makeStyles function and apply them in the CSS shorthand property of Material UI

When working with a button component, I pass props to customize its appearance: const StoreButton = ({ storeColor }) => { const borderBottom = `solid 3px ${storeColor}`; const classes = useStyles({ borderBottom }); return ( <Button varian ...

How come when you add ({}+{}) it equals to "[object Object][object Object]"?

I ran the following code: {}+{} = NaN; ({}+{}) = "[object Object][object Object]"; What is the reason behind the difference in result when adding ()? ...

Implement real-time reporting functionality in Selenium

I have been working on implementing a run-time reporting mechanism for my automated test cases created using Java with Selenium and TestNG. The test results and details are stored in a MySQL database. Although I can successfully insert the test results in ...

Implementing icon display upon click in a Meteor application

Currently, I am in the process of developing an application using meteor and within one of the templates, I have the following code snippet. <h3> <b> <a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a> </b> ...

Attempting to apply the 'Tw Cen MT Condensed Extra Bold' typeface using CSS styling

I'm having trouble getting the 'Tw Cen MT Condensed Extra Bold' font to work in my website header. Even when I try to style it with bold, it just doesn't look right. I created the banner in Photoshop and now I want to recreate the text ...

Submitting hidden values and multiple values with checkboxes in HTML

Is there a way to link multiple form fields with one checkbox for submission? For example: <input type=hidden name=code value="cycle_code" /> <input type=checkbox name=vehicle value="cycle" /> <input type=hidden name=code value="car_code" ...

What is the best way to ensure that a navbar dropdown appears above all other elements on

I'm having trouble creating a navbar dropdown with material design. The dropdown is working fine, but the issue I'm facing is that other elements are floating above it. https://i.stack.imgur.com/aJ0BH.png What I want is for the dropdown to floa ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

Aligning container divs at the center in various screen resolutions

I recently constructed a portfolio website using Bootstrap and Isotope JS. In my layout, I have a container div which works perfectly when viewed on a desktop browser - displaying 3 divs in one line. However, the issue arises when the resolution changes an ...