尝试通过 EF Core 在我的数据库中添加内容时出现此错误。
System.InvalidOperationException: 'No suitable constructor found for entity type 'HealthCheck'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'hctype' in 'HealthCheck(string title, string hctype, string link)'.'
这是我的健康检查类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Application.Models
{
public class HealthCheck
{
public HealthCheck(string title, string hctype, string link)
{
Title = title;
HCType = hctype;
Link = link;
}
public int Id { get; set; }
public string Title { get; set; }
public string HCType { get; set; }
public string Link { get; set; }
}
}
我的 RepositoryContext
using Microsoft.EntityFrameworkCore;
using Application.Models;
namespace Application.Repository
{
public class RepositoryContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=healthcheck;Integrated Security=True");
}
//public DbSet<HealthCheck> HealthChecks { get; set; }
//public DbSet<UserHealthCheck> UserHealthChecks { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<HealthCheck>().ToTable("HealthCheck");
modelBuilder.Entity<UserHealthCheck>().ToTable("UserHealthCheck");
}
}
}
我的仓库
using Application.Models;
namespace Application.Repository
{
public class Repository
{
public void InsertHealthCheck(HealthCheck healthCheck)
{
using (var db = new RepositoryContext())
{
db.Add(healthCheck);
db.SaveChanges();
}
}
}
}
这是调用“InsertHealthCheck()”的地方
[Route("/api/HealthCheck/Website")]
[HttpPost]
public ActionResult WebsiteStatus([FromBody] WebsiteDataModel websiteData)
{
HealthCheck data = new HealthCheck(websiteData.Title, "Website", websiteData.Url);
try
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(websiteData.Url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
HttpStatusCode HealthCheckStatusCode = myHttpWebResponse.StatusCode;
myHttpWebResponse.Close();
return Ok(HealthCheckStatusCode);
}
catch(UriFormatException)
{
return Ok("Check url.");
}
catch (Exception)
{
return Ok("400");
}
finally
{
repository.InsertHealthCheck(data);
}
}
如果你能帮我一把,我将不胜感激,如果你需要我发布代码的任何其他部分,请询问。
另外,我真的刚刚开始学习 EF Core,所以如果我做了一些非常愚蠢的事情,请指出来
最佳答案
提供一个无参数的构造函数可以避免这个问题,但这并不是 OP 案例中错误的真正原因。 EF Core 2.1 and higher uses a strict convention to map constructor parameters to property names of the entity.它期望构造函数参数的名称是 Pascal 大小写中属性名称的真正驼峰式表示。如果您将参数名称从“hctype”更改为“hCType”,您应该不会收到错误,并且不必必须提供无参数的构造函数,如果您的领域驱动设计方法表明它会出现问题这样做。
但是,如果您只是为了方便而提供参数化构造函数,但调用者能够使用“new”运算符实例化 HealthCheck 并无不妥,则只需添加无参数构造函数即可。
关于c# - 系统.InvalidOperationException : 'No suitable constructor found for entity type ' HealthCheck',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55838188/