尝试通过EF Core在数据库中添加某些内容时出现此错误。
System.InvalidOperationException:'找不到适合的构造函数
实体类型“ HealthCheck”。以下构造函数具有参数
不能绑定到实体类型的属性:无法绑定
“ HealthCheck(字符串标题,字符串hctype,字符串链接)”中的“ hctype”。
这是我的HealthCheck课:
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,因此,如果我做过一些非常愚蠢的事情,请指出来
最佳答案
您缺少空的构造函数:
public class HealthCheck
{
// here
public 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; }
}
这样尝试