Seeder#
填充数据到数据库中
定义Seeder#
在CleanArchitecture.Infrastructure定义Seeder类
namespace CleanArchitecture.Infrastructure.Seeders;
public interface IRestaurantSeeder
{
Task Seed();
}
using CleanArchitecture.Domain.Entities;
using CleanArchitecture.Infrastructure.Persistence;
namespace CleanArchitecture.Infrastructure.Seeders;
internal class RestaurantSeeder(RestaurantsDbContext dbContext) : IRestaurantSeeder
{
public async Task Seed()
{
if (await dbContext.Database.CanConnectAsync())
{
if (!dbContext.Restaurants.Any())
{
var restaurants = GetRestaurants();
dbContext.Restaurants.AddRange(restaurants);
await dbContext.SaveChangesAsync();
}
}
}
private IEnumerable<Restaurant> GetRestaurants()
{
List<Restaurant> restaurants = [
new()
{
Name = "KFC",
Category = "Fast Food",
Description =
"KFC (short for Kentucky Fried Chicken) is an American fast food restaurant chain headquartered in Louisville, Kentucky, that specializes in fried chicken.",
ContactEmail = "contact@kfc.com",
HasDelivery = true,
Dishes =
[
new ()
{
Name = "Nashville Hot Chicken",
Description = "Nashville Hot Chicken (10 pcs.)",
Price = 10.30M,
},
new ()
{
Name = "Chicken Nuggets",
Description = "Chicken Nuggets (5 pcs.)",
Price = 5.30M,
},
],
Address = new ()
{
City = "London",
Street = "Cork St 5",
PostalCode = "WC2N 5DU"
}
},
new ()
{
Name = "McDonald",
Category = "Fast Food",
Description =
"McDonald's Corporation (McDonald's), incorporated on December 21, 1964, operates and franchises McDonald's restaurants.",
ContactEmail = "contact@mcdonald.com",
HasDelivery = true,
Address = new Address()
{
City = "London",
Street = "Boots 193",
PostalCode = "W1F 8SR"
}
}
];
return restaurants;
}
}
ServiceCollectionExtensions新增Seeder#
using CleanArchitecture.Infrastructure.Persistence;
using CleanArchitecture.Infrastructure.Seeders;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CleanArchitecture.Infrastructure.Extensions;
public static class ServiceCollectionExtensions
{
public static void AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<RestaurantsDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("RestaurantsDb")));
services.AddScoped<IRestaurantSeeder, RestaurantSeeder>();
}
}
在API配置#
Program.cs
// other code
var scope = app.Services.CreateScope();
var seeder = scope.ServiceProvider.GetRequiredService<IRestaurantSeeder>();
await seeder.Seed();
// other code
运行项目,数据库中应该有数据