468,790 Members | 1,913 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,790 developers. It's quick & easy.

C#- Error in DbContext

I work at Blazor (C #) Server- Side. I am trying to save data to a database when registering a user (when I press the register button), but the following error occurs:
System.NullReferenceException: 'The object reference is not set on the object instance.' <> 4__this._dataContext.

I read on the Internet about that mistake, but I couldn't figure out what the problem was with me.

Find the code snippets below:

Register.razor:

Expand|Select|Wrap|Line Numbers
  1. @page "/register"
  2.  
  3. @using TestBlazor.Models
  4. @using TestBlazor.Data
  5.  
  6. @*@inject IToDoListService user*@
  7.  
  8. <br />
  9. <br />
  10.  
  11. <h3><b>Register</b></h3>
  12. <br />
  13.  
  14. <EditForm class="needs-validation" Model="@_user" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit">
  15.     <div class="alert @StatusClass">@StatusMessage</div>
  16.     <DataAnnotationsValidator />
  17.     <ValidationSummary />
  18.     <div class="form-group">
  19.         <p><b>User name</b></p>
  20.         <input id="username" class="solid" name="username" placeholder="Your username.." @bind-value="_user.UserName" />
  21.         <ValidationMessage For="@(() => @_user.UserName)"></ValidationMessage>
  22.     </div>
  23.     <div class="form-group">
  24.         <p><b>Password</b></p>
  25.         <input type="password" class="solid" id="password" placeholder="Your password.." @bind-value="_user.Password" />
  26.         <ValidationMessage For="@(() => @_user.Password)"></ValidationMessage>
  27.     </div>
  28.     <div class="form-group">
  29.         <p><b>Email</b></p>
  30.         <input id="email" class="solid" placeholder="you@example.com" @bind-value="_user.Email" />
  31.         <ValidationMessage For="@(() => @_user.Email)"></ValidationMessage>
  32.     </div>
  33.     <div class="form-group">
  34.         <p><b>Company</b></p>
  35.         <input id="company" class="solid" placeholder="Your company.." @bind-value="_user.Company" />
  36.         <ValidationMessage For="@(() => @_user.Company)"></ValidationMessage>
  37.     </div>
  38.  
  39.  
  40.     <br />
  41.  
  42.     <button disabled="@loading" class="btn btn-primary" onclick="AddUser">
  43.  
  44.         @if (loading)
  45.         {
  46.             <span class="spinner-border spinner-border-sm mr-1"></span>
  47.             <NavLink href="/login" class="btn btn-link">Register</NavLink>
  48.         }
  49.         Register
  50.     </button>
  51.     <NavLink href="/login" class="btn btn-link">Login</NavLink>
  52. </EditForm>
  53.  
  54.  
  55.  
  56. @code {
  57. private User _user = new User();
  58.  
  59. private string StatusMessage;
  60. private string StatusClass;
  61.  
  62. private bool loading;
  63. private readonly AppDbContext _dataContext;
  64.  
  65.  
  66. private void OnValidSubmit()
  67. {
  68.     if (loading == true)
  69.     {
  70.         Console.WriteLine("You have successfully registered!");
  71.     }
  72.  
  73.     else
  74.     {
  75.         loading = false;
  76.         Console.WriteLine("Check your information again!");
  77.     }
  78. }
  79.  
  80. //protected void HandleValidSubmit()
  81. //{
  82. //    StatusClass = "alert-info";
  83. //    StatusMessage = " You have successfully registered! Please click the Login button to log in!";
  84.  
  85. @*}*@
  86.  
  87.  
  88. private async void HandleValidSubmit()
  89. {
  90.     try
  91.     {
  92.         _dataContext.User.Add(_user); //error in this record System.NullReferenceException: 'Object reference not set to an instance of an object.' <> 4__this._dataContext was null.
  93.  
  94.         await _dataContext.SaveChangesAsync();
  95.         }
  96.         catch
  97.         {
  98.             base.StateHasChanged();
  99.         }
  100.         _user = new User();
  101.         base.StateHasChanged();
  102.         }
  103.  
  104.  
  105.         protected void HandleInvalidSubmit()
  106.         {
  107.         StatusClass = "alert-danger";
  108.         StatusMessage = " Check your information again!";
  109.         }
  110.  
  111.  
  112.         //public bool doesCompanyExist(string Company)
  113.         //{
  114.         //    try
  115.         //    {
  116.  
  117.         //        if (Company != null)
  118.         //        {
  119.         //            return true;
  120.         //        }
  121.  
  122.         //    }
  123.         //    catch (Exception)
  124.         //    {
  125.         //        return false;
  126.         //    }
  127.  
  128.         //    return false;
  129.  
  130.         //}
  131.  
  132.         }
  133.  
User.cs:

Expand|Select|Wrap|Line Numbers
  1. [Table("Users")]
  2.     public class User
  3.  
  4.     {
  5.  
  6.         [Display(AutoGenerateField = false)]
  7.         public int UserId { get; set; }
  8.  
  9.         [Display(Name = "UserName")]
  10.         [Required(ErrorMessage = "UserName is required.")]
  11.         public string UserName { get; set; }
  12.  
  13.         [Display(Name = "Password")]
  14.         [Required]
  15.         [MinLength(8, ErrorMessage = "password must be atleast 8 characters")]
  16.         [DataType(DataType.Password)]
  17.         public string Password { get; set; }
  18.  
  19.         [Display(Name = "Email")]
  20.         [Required(ErrorMessage = "Email is required.")]
  21.         public string Email { get; set; }
  22.  
  23.         [Display(Name = "Company")]
  24.         [StringLength(255)]
  25.         [Required(ErrorMessage = "Company is required.")]
  26.         [Remote("doesCompanyExist", "Company", HttpMethod = "POST", ErrorMessage = "Company already exists. Please enter a different company.")]
  27.         public string Company { get; set; }
  28.  
  29.         public User GetRegisteredUser()
  30.         {
  31.             return new User
  32.             {
  33.                 UserName = UserName,
  34.                 Password = Password,
  35.                 Email = Email,
  36.                 Company = Company,
  37.  
  38.             };
  39.         }
  40.  
  41.     }
  42.  
AppDbContext.cs:

Expand|Select|Wrap|Line Numbers
  1. public class AppDbContext : DbContext
  2.     {
  3.         public AppDbContext()
  4.         {
  5.  
  6.         }
  7.  
  8.         public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
  9.         {
  10.         }
  11.  
  12.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  13.         {
  14.             if (!optionsBuilder.IsConfigured)
  15.             {
  16.                 optionsBuilder.UseSqlServer("Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=testblazor;Integrated Security=True;");
  17.             }
  18.         }
  19.  
  20.         //protected override void OnModelCreating(ModelBuilder modelBuilder)
  21.         //{
  22.         //    base.OnModelCreating(modelBuilder);
  23.         //    modelBuilder.Entity<User>()
  24.         //}
  25.  
  26.         public DbSet<User> User { get; set; }
  27.         public DbSet<Item> Items { get; set; }
  28.  
  29.  
  30.     }
  31.  
Jul 1 '21 #1
0 1292

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

7 posts views Thread by p | last post: by
1 post views Thread by developer | last post: by
15 posts views Thread by madhu.ab | last post: by
5 posts views Thread by yashu0209 | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.