Search code examples
c#sql-serverasp.net-mvcdatabaseasp.net-core

Unable to create a 'DbContext' of type NULL. The exception 'Object reference not set to an instance of an object.'


I have a problem with add-migration for my database in ASP.NET Core 8.0.

Here is the code

ApplicationDbContext:

    public ApplicationDbContext(DbContextOptions<DbContext> options) : base(options)
    {
    }
    public DbSet<Single1> Singles { get; set; }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Person> Persons { get; set; }
    public DbSet<Day> Days { get; set; }
    public DbSet<Month> Months { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Single1>().HasData(
            new Single1 { SetId = 1, UserId = 1, SubcriptionDate = new DateTime(2020, 12, 12), Set1 = 1, Set2 = 0, Set3 = 1 }
            );
        modelBuilder.Entity<Department>().HasData(
            new Department { DepartmentId = 1, DepartmentName = "IT", PersonalIds = { 1 } }
            );
        modelBuilder.Entity<Person>().HasData(
            new Person { Name = "Trung", PersonalId = 1, Set1 = 1, Set2 = 1, Set3 = 1 }
            );
        modelBuilder.Entity<Day>().HasData(
            new Day { DayId= 1, Date = new DateTime(2020, 12, 12), DepartmentId = 1 }
            );
        modelBuilder.Entity<Month>().HasData(
            new Month { MonthId = 1, Month1 = new DateTime(2020, 12, 12), DepartmentId = 1 }
            );
    }
}

Day.cs:

public class Day
{
    [Key]
    [Required]
    public int DayId { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString ="{0:DD/MM/yyyy}",ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }
    [Required]
    public int DepartmentId { get; set; }
    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }

}

Month.cs:

public class Month
{
    [Key]
    public int MonthId {  get; set; }
    [DisplayFormat(DataFormatString = "{0:MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime Month1 { get; set; }
    public int DepartmentId { get; set; }
    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }
}

Person.cs:

public class Person
{
    [Key]
    public int PersonalId { get; set; }
    public string Name {  get; set; }
    [DefaultValue(0)]
    public int Set1 { get; set; }
    [DefaultValue(0)]
    public int Set2 { get; set; }
    [DefaultValue(0)]
    public int Set3 { get; set; }
}

Department.cs:

public class Department
{
    [Key]
    public int DepartmentId { get; set; }
    [Required]
    public virtual List<int> PersonalIds { get; set; }
    [ForeignKey("PersonalId")]
    public virtual List<Person> Persons { get; set; }
    public string? DepartmentName { get; set; }
}

Single.cs:

public class Single1
{
    [Key]
    public int SetId { get; set; }
    [Required]
    public int UserId { get; set; }
    [Required]
    [DisplayFormat(DataFormatString = "{0:DD/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime SubcriptionDate { get; set; }
    [Range(0, 10, ErrorMessage ="Chỉ có tối đa 10 xuất cho 1 người")]
    [DefaultValue(0)]
    public int Set1 { get; set; }
    [Range(0, 10, ErrorMessage = "Chỉ có tối đa 10 xuất cho 1 người")]
    [DefaultValue(0)]
    public int Set2 { get; set; }
    [Range(0, 10, ErrorMessage = "Chỉ có tối đa 10 xuất cho 1 người")]
    [DefaultValue(0)]
    public int Set3 { get; set; }
}

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=Admin;Database=BTAnCaRedo;Trusted_Connection=True;TrustServerCertificate=True"
  }
}

program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddRazorPages();
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
    pattern: "{area=User}/{controller=Home}/{action=Index}/{id?}");

app.Run();

I try everything available immediately on Google and videos on Youtube but still can't fix it. The Error in the title keeps popping up over and over. The default project is also correct so I can't see where the problem lies.


Solution

  • Double check that connection string is correct. Try adding "Encrypt=Yes;" to it. We had that error before and it turns out in ASP.NET Core 8.0 "Encrypt=Yes;" in connection string fixed it.