我正在try 使用.NET6创建我自己的Web API,但在将数据放入数据库之前,我收到了一个错误
System.InvalidOperationException:‘无法创建类型为’Hotelum.HotelsSeeder‘的实例,因为无法绑定一个或多个参数.构造函数参数必须具有相应的属性.不支持字段.缺少的属性为:‘dbContext’
using Hotelum.Entities;
using Microsoft.EntityFrameworkCore;
namespace Hotelum
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<IWeatherForecastService, WeatherForecastService>();
builder.Services.AddControllers();
builder.Services.AddDbContext<HotelsDbContext>();
builder.Services.AddScoped<HotelsSeeder>();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.Configuration.Get<HotelsSeeder>(); //Error appears
HotelsSeeder seeder = app.Services.GetRequiredService<HotelsSeeder>();
seeder.Seed();
app.UseHttpsRedirection();
//app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
我一直在寻找任何解决方案,但都找不到.
下面是数据所在的类
using Hotelum.Entities;
namespace Hotelum
{
public class HotelsSeeder
{
private readonly HotelsDbContext _dbContext;
public HotelsSeeder(HotelsDbContext dbContext)
{
_dbContext = dbContext;
}
public void Seed()
{
if (_dbContext.Database.CanConnect())
{
if (!_dbContext.Hotels.Any())
{
var hotel = GetHotels();
_dbContext.Hotels.AddRange(hotel);
_dbContext.SaveChanges();
}
}
}
private IEnumerable<Hotels> GetHotels()
{
var hotel = new List<Hotels>();
new Hotels()
{
Name = "Avocado",
Description = "Perfect for family, chill and drinks",
Category = "Holidays",
IsItOpen = true,
ContactEmail = "contact@avocado.com",
ContactNumber = "123456789",
Rooms = new List<Rooms>()
{
new Rooms()
{
Name = "Król",
Description = "Dla bogatych",
Price = 8549098M,
NumberOfRooms = 1,
},
new Rooms()
{
Name = "Królowa",
Description = "Dla mniej bogatych",
Price = 89098M,
NumberOfRooms = 5,
},
new Rooms()
{
Name = "Standart",
Description = "Dla standartów",
Price = 88M,
NumberOfRooms = 25,
},
},
Address = new Address()
{
City = "Wwa",
Street = "Poznanska",
PostalCode = "10-092"
}
};
new Hotels()
{
Name = "Abada",
Description = "Perfect for horrors",
Category = "Horros",
IsItOpen = true,
ContactEmail = "contact@abada.com",
ContactNumber = "123456789",
Rooms = new List<Rooms>
{
new Rooms()
{
Name = "Bieda",
Description = "Dla odważnych",
Price = 8M,
NumberOfRooms = 1,
},
new Rooms()
{
Name = "Mniejsza bieda",
Description = "Dla normalnych",
Price = 98M,
NumberOfRooms = 5,
},
new Rooms()
{
Name = "Bogato",
Description = "Dla bogatych",
Price = 88M,
NumberOfRooms = 25,
}
},
Address = new Address()
{
City = "Poznan",
Street = "Warszawska",
PostalCode = "50-792"
}
};
return hotel;
}
}
}
我试图用配置来实现它,但找不到一种方法来使用它,我试图为它添加AddDbContext
,也不起作用.