csharp
Код: Выделить всё
using eTickets.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
namespace eTickets.Data
{
public class AppDbInitializer
{
public static void Seed(IServiceProvider services)
{
// Create a scope to resolve services
using (var scope = services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
// Apply migrations
context.Database.Migrate();
// Seed Cinemas if empty
if (!context.Cinemas.Any())
{
context.Cinemas.AddRange(new List()
{
new Cinema()
{
Name = "Cinema 1",
Logo = "http://dotnethow.net/images/cinemas/cinema-1.jpeg",
Description = "This is the description of the first cinema"
},
new Cinema()
{
Name = "Cinema 2",
Logo = "http://dotnethow.net/images/cinemas/cinema-2.jpeg",
Description = "This is the description of the second cinema"
},
new Cinema()
{
Name = "Cinema 3",
Logo = "http://dotnethow.net/images/cinemas/cinema-3.jpeg",
Description = "This is the description of the third cinema"
},
new Cinema()
{
Name = "Cinema 4",
Logo = "http://dotnethow.net/images/cinemas/cinema-4.jpeg",
Description = "This is the description of the fourth cinema"
},
new Cinema()
{
Name = "Cinema 5",
Logo = "http://dotnethow.net/images/cinemas/cinema-5.jpeg",
Description = "This is the description of the fifth cinema"
}
});
// Save to database
context.SaveChanges();
}
}
}
}
}
csharp
Код: Выделить всё
using System; // For IServiceProvider
csharp
Код: Выделить всё
namespace eTickets.Models
{
public class Cinema
{
public int Id { get; set; }
public string Name { get; set; }
public string Logo { get; set; }
public string Description { get; set; }
// Add other properties as needed
// Relationships
public List Movies { get; set; }
}
}
csharp
Код: Выделить всё
// Seed Actors
if (!context.Actors.Any())
{
context.Actors.AddRange(new List()
{
new Actor()
{
FullName = "Actor 1",
Bio = "This is the Bio of the first actor",
ProfilePictureURL = "http://dotnethow.net/images/actors/actor-1.jpeg"
},
// Add more actors...
});
context.SaveChanges();
}
// Seed Producers
if (!context.Producers.Any())
{
context.Producers.AddRange(new List
()
{
new Producer()
{
FullName = "Producer 1",
Bio = "This is the Bio of the first producer",
ProfilePictureURL = "http://dotnethow.net/images/producers/producer-1.jpeg"
},
// Add more producers...
});
context.SaveChanges();
}
Эта полная логика заполнения будет:
- Применять любые ожидающие миграции
- Проверять, пуста ли таблица Cinemas
- Добавить 5 примеров кинотеатров, если таблица пуста
- Сохранить изменения в базе данных
image.png
PNG 135,79 КБ
что должно я ввожу в свое тело
Вот что вы должны ввести в раздел тела вашего вопроса о переполнении стека (более 220 символов):
Подведите итог проблемы
Я создаю приложение ASP.NET Core MVC (eTickets) и пытаюсь заполнить свою базу данных с помощью класса AppDbInitializer. Когда я запускаю приложение, я получаю сообщение об ошибке: System.InvalidOperationException: свойство ConnectionString не было инициализировано. Это происходит при вызове context.Database.Migrate() в моем исходном методе. Моя цель — применить миграцию и загрузить исходные данные, такие как Cinemas, в базу данных.
Опишите, что вы пробовали
- Я проверил, что мой файл appsettings.json имеет действительную строку подключения в ConnectionStrings:DefaultConnection
- Я зарегистрировал свой AppDbContext в Startup.cs с использованием сервисов.AddDbContext
- Я вызываю метод семени в Program.cs после создания узла
- Я проверил, что мой конструктор AppDbContext принимает DbContextOptions
- Я попробовал методы обеспеченияCreated() и Migrate()
Мой Startup.cs Метод ConfigurationServices:
csharp
Код: Выделить всё
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
json
Код: Выделить всё
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=eTicketsDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
csharp
Код: Выделить всё
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService();
AppDbInitializer.Seed(services);
}
host.Run();
}
csharp
Код: Выделить всё
public static void Seed(IServiceProvider services)
{
using (var scope = services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService();
context.Database.Migrate(); // ERROR OCCURS HERE
if (!context.Cinemas.Any())
{
context.Cinemas.AddRange(...);
context.SaveChanges();
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... onnections
Мобильная версия