Невозможно создать DbContext типа NULL. Исключение «Ссылка на объект не установлена ​​на экземпляр объекта».C#

Место общения программистов C#
Ответить
Anonymous
 Невозможно создать DbContext типа NULL. Исключение «Ссылка на объект не установлена ​​на экземпляр объекта».

Сообщение Anonymous »

У меня возникла проблема с добавлением миграции для моей базы данных в ASP.NET Core 8.0.
Вот код
ApplicationDbContext:< /p>

Код: Выделить всё

    public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Singles { get; set; }
public DbSet Departments { get; set; }
public DbSet
 Persons { get; set; }
public DbSet Days { get; set; }
public DbSet Months { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().HasData(
new Single1 { SetId = 1, UserId = 1, SubcriptionDate = new DateTime(2020, 12, 12), Set1 = 1, Set2 = 0, Set3 = 1 }
);
modelBuilder.Entity().HasData(
new Department { DepartmentId = 1, DepartmentName = "IT", PersonalIds = { 1 } }
);
modelBuilder.Entity().HasData(
new Person { Name = "Trung", PersonalId = 1, Set1 = 1, Set2 = 1, Set3 = 1 }
);
modelBuilder.Entity().HasData(
new Day { DayId= 1, Date = new DateTime(2020, 12, 12), DepartmentId = 1 }
);
modelBuilder.Entity().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 PersonalIds { get; set; }
[ForeignKey("PersonalId")]
public virtual List
 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(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddRazorPages();
builder.Services.AddScoped(typeof(IRepository), typeof(Repository));
builder.Services.AddTransient();

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();
Я пробую все, что доступно в Google и видео на Youtube, но так и не могу это исправить. Ошибка в заголовке выскакивает снова и снова. Проект по умолчанию также правильный, поэтому я не вижу, в чем проблема.

Подробнее здесь: https://stackoverflow.com/questions/786 ... erence-not
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»