Это бросается, когда я запускаю свое приложение: я написал сеялку данных, чтобы получить некоторые данные в моей базе данных. Я оценил этот класс в моем конфигурационном процессе и использовал его в методе Configure .
public void ConfigureServices(IServiceCollection services) {
services.Configure(options => {
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped();
services.AddScoped();
services.AddScoped();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,DataSeeder seeder) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
} else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseStatusCodePages();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseCookiePolicy();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
seeder.SeedData();
}
< /code>
И в этом классе ошибочна ошибка: < /p>
public class DataSeeder {
#region Fields
private readonly ApplicationDbContext _context;
private Random random;
private ISet _set;
#endregion
#region Constructor
public DataSeeder(ApplicationDbContext context) {
_context = context;
random = new Random();
_set = new HashSet();
}
#endregion
#region Methods
public void SeedData() {
_context.Database.EnsureDeleted();
if (_context.Database.EnsureCreated()) { //**on this line**
AddCodes();
//reservations
Reservation r1 = new Reservation(new DateTime(2019, 2, 21), "Robbe van de Vyver", "Kip met rijst en currysaus", true, "");
_context.Reservations.Add(r1);
_context.SaveChanges();
}
}
private void AddCodes() {
if (_context.Codes.Count()
Но это не единственное время, когда эта выполняемая ножка бросается, она также бросается, когда я пытаюсь загрузить определенную страницу моего приложения: < /p>
public class ChezMoutController : Controller {
private IRatingRepository _ratingRepository;
private IReservationRepository _reservationRepository;
public ChezMoutController(IRatingRepository ratingRepository, IReservationRepository reservationRepository) {
_ratingRepository = ratingRepository;
_reservationRepository = reservationRepository;
}
public IActionResult Index() {
ViewData["foodAverage"] = _ratingRepository.GetAll().Select(r => r.FoodRating).Average();
ViewData["atmosphereAverage"] = _ratingRepository.GetAll().Select(r => r.AtmosphereRating).Average();
ViewData["reservations"] = _reservationRepository.GetAll();
ViewData["DatesLeft"] = new List() { };
return View(_ratingRepository.GetAll());
}
}
< /code>
Каждый раз, когда я пытаюсь загрузить представление, подключенное к этому индексу в этом контроллере, то же самое, что и то же самое, что вызывает здесь: < /p>
public class RatingRepository : IRatingRepository {
private readonly ApplicationDbContext _context;
public RatingRepository(ApplicationDbContext context) {
_context = context;
}
public void Add(Rating rating) {
var any = _context.Ratings.Any(r => r.RatingId == rating.RatingId);
if (!any) {
_context.Add(rating);
}
}
public IEnumerable GetAll() {
return _context.Ratings.ToList(); //**on this line**
}
public void Remove(Rating rating) {
var any = _context.Ratings.Any(r => r.RatingId == rating.RatingId);
if (any) {
_context.Remove(rating);
}
}
public void SaveChanges() {
_context.SaveChanges();
}
}
< /code>
(интерфейс этот класс реализует

public interface IRatingRepository {
IEnumerable GetAll();
void Add(Rating rating);
void Remove(Rating rating);
void SaveChanges();
}
< /code>
Я думаю, что это как -то связано с моим классом рейтинга: < /p>
public class Rating {
#region Fields
private double _foodRating;
private double _atmosphereRating;
#endregion
#region Properties
public int RatingId { get; set; }
public double FoodRating {
get {
return _foodRating;
}
private set {
if (value < 0.0 || value > 5.0) {
throw new ArgumentException("Give a score between 0 and 5 please.");
}
_foodRating = value;
}
}
public double AtmosphereRating {
get {
return _atmosphereRating;
}
private set {
if (value < 0.0 || value > 5.0) {
throw new ArgumentException("Give a score between 0 and 5 please.");
}
_atmosphereRating = value;
}
}
public string PersonalMessage { get; set; } //not mandatory
public string Suggestions { get; set; } //not mandatory
#endregion
#region Constructors
public Rating() {
}
public Rating(double foodRating, double atmosphereRating, string personalMessage = null, string suggestions = null):this() {
FoodRating = foodRating;
AtmosphereRating = atmosphereRating;
PersonalMessage = personalMessage;
Suggestions = suggestions;
}
#endregion
}
< /code>
Но я бы не знал, что делать, чтобы исправить это.
Любая помощь будет оценена! public class ApplicationDbContext : DbContext {
public DbSet Ratings { get; set; }
public DbSet Reservations { get; set; }
public DbSet Codes { get; set; }
public ApplicationDbContext(DbContextOptions options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.ApplyConfiguration(new RatingConfiguration());
modelBuilder.ApplyConfiguration(new ReservationConfiguration());
}
}
< /code>
ratingconfiguartion < /p>
public class RatingConfiguration : IEntityTypeConfiguration {
public void Configure(EntityTypeBuilder builder) {
builder.ToTable("Rating");
builder.HasKey(r => r.RatingId);
builder.Property(r => r.PersonalMessage)
.HasMaxLength(250)
.IsRequired(false);
builder.Property(r => r.Suggestions)
.HasMaxLength(250)
.IsRequired(false);
}
}
Подробнее здесь: https://stackoverflow.com/questions/544 ... ype-string