找不到适合实体类型字符串的构造函数。

26

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

完整异常:

System.InvalidOperationException:'未找到适用于实体类型“string”的合适构造函数。以下参数无法绑定到实体属性:'value'、'value'、'startIndex'、'length'、'value'、'value'、'startIndex'、'length'、'value'、'value'、'startIndex'、'length'、'value'、'startIndex'、'length'、'enc'、'c'、'count'、'value'。'

当我启动我的应用程序时就会抛出此异常:我编写了一个数据种子器来将一些数据放入我的数据库中。我已经将这个类限定在我的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());
    }
}

评分配置

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);
    }
}
7个回答

28

我遇到了类似的问题。

我在一个类中做了一些更改并删除了默认的类构造函数。尽管它从未被调用,但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
    }
}

4
自 EF Core 2.1 起,您不再需要为 EF Core 提供一个空的构造函数了。EF Core 文档 指出:__当 EF Core 创建实例时,它会首先调用默认的无参构造函数[...]。但是,如果 EF Core 找到一个带参数的构造函数[...],那么它将使用这些属性的值调用带参数的构造函数__。 - somethingRandom
至少将默认构造函数设置为私有的 - Patrick Koorevaar

22

问题在于您的上下文中,您有这行代码:

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

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


1
那么你会建议我做什么呢?创建一个具有字符串属性的 Code 类吗? - Mout Pessemier
这对于在这里的任何人来说都是不可能告诉你的,这是你的表格,你需要定义类。 - DavidG
好的,我会找到解决方案,非常感谢!一旦我能够,我会接受这个答案! - Mout Pessemier

2

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

解决方法: 不要更新现有的构造函数,而是添加一个重载的构造函数来处理新属性,这样在创建迁移时就不会出现错误了。

"Original Answer"的翻译是"最初的回答"


2
在我的情况下,这个错误在我更正映射的字段/属性大小写之后得到了解决。
我建议使用:
- 驼峰式命名法用于字段 - 帕斯卡命名法用于属性。即使你的属性名称像“DBProperty”,也要将其更改为“DbProperty”。

2

这个问题已经有部分回答了,但是在EF Core中有一个通用的指导方针需要与此问题相关的说明。

当你在实体类中定义一个实体时,你需要确保整个实体都是公共的和可访问的。例如:

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类型需要是一个具体的类,该类定义您希望成为表中列或与另一个表关系的各种属性。希望这能帮助某些人。

1

@DavidG和@BrownPony是正确的,但我想添加更多信息:

不可能像public Company (string companyName = "")这样在构造函数中添加默认值,但可以使用私有构造函数。

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments#example-1

public class Company
{
    private Company ( )
    {
    }

    public Company (string companyName)
    {
         // some code
    }
}

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/private-constructors

https://dev59.com/5lwZ5IYBdhLWcg3wWvRY#31543487


1

当我向实体模型添加新属性并在构造函数中设置该属性时,遇到了同样的问题。请验证构造函数的大小写模式是否与属性匹配。


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community
这并没有真正回答问题。如果您有不同的问题,可以通过点击提问来询问。如果您想在此问题有新回答时收到通知,您可以关注此问题。一旦您拥有足够的声望,您还可以添加悬赏以吸引更多注意力至此问题。- 来自审核 - John V

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接