473,473 Members | 1,856 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

C#- Error in DbContext

2 New Member
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
1 3703
akhilc2005
2 New Member
where is _dataContext objct getting initialized? I do not see it anywhere hence you are getting object reference error since its not initialized.

Befiore calling this you need to initailize.
Aug 21 '21 #2

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

Similar topics

13
by: deko | last post by:
I use this convention frequently: Exit_Here: Exit Sub HandleErr: Select Case Err.Number Case 3163 Resume Next Case 3376 Resume Next
7
by: p | last post by:
WE had a Crystal 8 WebApp using vs 2002 which we upgraded to VS2003. I also have Crystal 9 pro on my development machine. The web app runs fine on my dev machine but am having problems deploying....
1
by: developer | last post by:
Hi All I have made a .NET project. the files included are borland c++ files that i am migrate to VC++ .NET I am using Microsoft Visual C++ .NET 2003. the compilation goes through properly,...
2
by: f rom | last post by:
----- Forwarded Message ---- From: Josiah Carlson <jcarlson@uci.edu> To: f rom <etaoinbe@yahoo.com>; wxpython-users@lists.wxwidgets.org Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: ...
2
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I...
15
by: madhu.ab | last post by:
Hi All, I am getting the following errors when i am including header file winuser.h I dont know whats happening. How will an error occur in winuser.h?? Please help. \microsoft visual...
0
hyperpau
by: hyperpau | last post by:
Before anything else, I am not a very technical expert when it comes to VBA coding. I learned most of what I know by the excellent Access/VBA forum from bytes.com (formerly thescripts.com). Ergo, I...
5
by: yashu0209 | last post by:
I have an error occurring when i try to compile the program and the error is: D:\Program Files\visual studio 6.0\MSDev98\MyProjects\GLEnabledView\GLNew.cpp(164) : error C2653: 'CGLEnabledView' :...
2
by: randa zaghdan | last post by:
Hi I have a problem with my program in vc 2008 When I compile it, the following errors are listed. I try to resolve it but no hope Does any one can help me ? thanks . Linking......
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.