Я в некотором роде новичок в ядре инфраструктуры сущностей MVC, и я боролся с этим исключением, и я не знаю, что его вызывает.
Я всегда получаю одну и ту же ошибку: System.InvalidOperationException: 'Не найдено подходящего конструктора для типа объекта «Рейтинг».Следующие параметры не могут быть привязаны к свойствам объекта: «дата», «сообщение», «предложение». '
Ошибка генерируется в методе GetAll ():
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<Rating> GetAll() {
return _context.Ratings.ToList();
}
public IEnumerable<Rating> GetFirst(int amount) {
return GetAll().Take(amount).ToList();
}
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();
}
}
Это интерфейс, который реализует репозиторий:
public interface ICodeRepository {
IEnumerable<string> GetAll();
void Remove(string code);
void SaveChanges();
}
Это мой класс рейтинга:
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(double foodRating, double atmosphereRating, DateTime date, string message = null, string suggestion = null) {
FoodRating = foodRating;
AtmosphereRating = atmosphereRating;
PersonalMessage = message;
Suggestions = suggestion;
}
#endregion
}
Вот как я сопоставил его с базой данных:
public class RatingConfiguration : IEntityTypeConfiguration<Rating> {
public void Configure(EntityTypeBuilder<Rating> 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);
}
}
В моем ApplicationDb я предвидел DbSet, а в OnModelCreating я дал RatingConfiguration с.
Мне нужно привязать это к результату формы, так вот мой RatingViewModel:
public class RatingViewModel {
#region Properties
[Required]
[DataType(DataType.Text)]
[Display(Name = "How would you rate the food?")]
public double FoodRating { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "How would you rate the atmosphere?")]
public double AtmosphereRating { get; set; }
[Display(Name = "Personal message")]
[DataType(DataType.Text)]
[StringLength(250, ErrorMessage = "Suggestion is needs to be between 250 and 0 characters")]
public string PersonalMessage { get; set; }
[Display(Name = "Any suggestions for next time?")]
[DataType(DataType.Text)]
[StringLength(250,ErrorMessage = "Suggestion is needs to be between 250 and 0 characters")]
public string Suggestions { get; set; }
#endregion
#region Constructor
public RatingViewModel() {
}
public RatingViewModel(Rating rating) : this() {
FoodRating = rating.FoodRating;
AtmosphereRating = rating.AtmosphereRating;
PersonalMessage = rating.PersonalMessage;
Suggestions = rating.Suggestions;
}
#endregion
}
Теперь, если кто-нибудь из вас сможет найти причину этого исключения, пожалуйста, дайте мне знать.Если вам нужно что-то еще из моего кода, также дайте мне знать!