找不到适用于实体类型字符串的

时间:2019-01-28 10:37:55

标签: c# entity-framework-core

昨天,我来问她一个类似的问题,关于我自己制造的实体类型出现一些错误。我已修复了这些错误,但现在它在实体类型字符串上抛出了一个错误,我完全不知道如何解决此问题。

完全例外:

  

System.InvalidOperationException:'找不到适用于实体类型'string'的合适的构造函数。以下参数无法绑定到实体的属性:“值”,“值”,“ startIndex”,“长度”,“值”,“值”,“ startIndex”,“长度”,“值”,“值”,“ startIndex”,“长度”,“值”,“ startIndex”,“长度”,“ enc”,“ c”,“计数”,“值”。”

启动应用程序时会抛出该错误:我编写了一个数据播种器以在数据库中获取一些数据。我在ConfigureServices中定义了该类的范围,并在Configure方法中使用了它。

public void ConfigureServices(IServiceCollection services) {
        services.Configure<CookiePolicyOptions>(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<ApplicationDbContext>(options =>
           options.UseSqlServer(
               Configuration.GetConnectionString("DefaultConnection")));
        services.AddScoped<IRatingRepository, RatingRepository>();
        services.AddScoped<IReservationRepository, ReservationRepository>();
        services.AddScoped<DataSeeder>();
    }

    // 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();
    }

并且在此类中抛出了错误:

public class DataSeeder {
    #region Fields
    private readonly ApplicationDbContext _context;
    private Random random;
    private ISet<string> _set;
    #endregion

    #region Constructor
    public DataSeeder(ApplicationDbContext context) {
        _context = context;
        random = new Random();
        _set = new HashSet<string>();
    }
    #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() <= 5) {
            char[] characters = "azertyuiopqsdfghjklmwxcvbn,;:=?+-./+~ù%^$*&éè!çà|@#0123456789AZERTYUIOPQSDFGHJKLMWXCVBN".ToArray();
            for (int i = 0; i < 25; i++) {
                string code = "";
                for (int j = 0; j < 4; i++) {
                    code += characters[random.Next(0, characters.Length)];
                }
                _set.Add(code);
            }
            _context.Codes.AddRange(_set);
            _context.SaveChanges();
        }
    } 
    #endregion

但这不是唯一一次引发这种错误的想法,当我尝试加载应用程序的特定页面时也会引发这种错误:

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<DateTime>() { };
        return View(_ratingRepository.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(); //**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();
    }
}

(此类实现的接口:)

    public interface IRatingRepository {
    IEnumerable<Rating> GetAll();
    void Add(Rating rating);
    void Remove(Rating rating);
    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() {

    }

    public Rating(double foodRating, double atmosphereRating, string personalMessage = null, string suggestions = null):this() {
        FoodRating = foodRating;
        AtmosphereRating = atmosphereRating;
        PersonalMessage = personalMessage;
        Suggestions = suggestions;
    }
    #endregion

}

但是我不知道该如何解决。 任何帮助将不胜感激!

ApplicationDbContext:

 public class ApplicationDbContext : DbContext {
    public DbSet<Rating> Ratings { get; set; }
    public DbSet<Reservation> Reservations { get; set; }
    public DbSet<string> Codes { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.ApplyConfiguration(new RatingConfiguration());
        modelBuilder.ApplyConfiguration(new ReservationConfiguration());
    }
}

RatingConfiguartion

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);
    }
}

4 个答案:

答案 0 :(得分:5)

也有类似的问题。

我有一个类,正在做一些更改,并删除了默认的类构造函数。尽管它从未被调用过,但EF仍然需要它,否则您将得到找不到合适的构造函数异常

public class Company
{
    public  Company ( )
    {
      // ef needs this constructor even though it is never called by 
     // my code in the application. EF needs it to set up the contexts

      // Failure to have it will result in a 
      //  No suitable constructor found for entity type 'Company'. exception
    }

    public Company ( string _companyName , ......)
    {
         // some code
    }
}

答案 1 :(得分:2)

问题出在您的上下文中,您有以下一行:

public DbSet<string> Codes { get; set; }

您需要为实体使用一个具体的类,不能使用string

答案 2 :(得分:1)

这是我在实体中添加新属性并更新现有构造函数并将新属性作为参数传递时遇到的相同问题

修复: 与其更新现有的构造函数,不如添加具有新属性的重载构造函数,并且在创建迁移时此错误已消失

答案 3 :(得分:0)

对此已经部分回答,但是在EF Core中有关于该问题的一般准则。

在Entity类中定义Entity时,需要确保整个事物都是公共的且可访问的。例如,

public class GroupMap
    {
        [Key] public int Id { get; set; }
        public string GroupId { get; set; }
    }

有两个属性,Id(具有冗余的[Key]批注)和GroupId。仅考虑GroupId,它必须是公共属性,并且必须同时定义其getter和setter。

所以这将失败:

public class GroupMap
    {
        [Key] public int Id { get; set; }
        private string GroupId { get; set; }  // private property not allowed
    }

这将会:

public class GroupMap
    {
        [Key] public int Id { get; set; }
        public string GroupId { get; } // setter must be defined
    }

由于EF Core是ORM,因此您还需要确保该属性类型对于数据库而言是有意义的(尽管我在这里不能提供太多详细信息)。最后,如其他地方所述,您还需要提供正确的上下文定义。所有相同的规则都适用。

例如:

public DbSet<Item> Items { get; set; } // public, and getter & setter defined

正如其他地方所述,DbSet类型必须是一个具体的类,该类定义您希望成为表中的列或与另一个表的关系的各种属性。

希望可以帮助某个人。