System.InvalidOperationException: 'No suitable constructor found for entity type 'HealthCheck'

asp.net c# entity-framework-core model-view-controller

Question

I get this error when trying to add something on my db through 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)'.'

This is my HealthCheck class:

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

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

My Repository

using Application.Models;

namespace Application.Repository
{
    public class Repository
    {
        public void InsertHealthCheck(HealthCheck healthCheck)
        {
            using (var db = new RepositoryContext())
            {
                db.Add(healthCheck);
                db.SaveChanges();
            }
        }
    }
}

And this is where "InsertHealthCheck()" is being called from

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

If you can give me a hand I would appreciate it, if you need for me to post any other part of the code just ask.

Also, I literally just started learning EF Core, so if I did something really stupid, point it out

1
2
4/24/2019 8:49:08 PM

Accepted Answer

You are missing empty constructor:

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


}

try it like that

0
4/24/2019 8:54:45 PM

Popular Answer

Providing a parameterless constructor avoids the problem, but it was not the true cause of the error in the OP's case. EF Core 2.1 and higher uses a strict convention to map constructor parameters to property names of the entity. It expects a constructor parameter's name to be a true camel-case representation of a property name in Pascal-case. If you change the parameter name from "hctype" to "hCType", you should not get the error and not have to provide a parameterless constructor if your approach to domain-driven design dictates that it would be problematic to do so.

If, however, you were simply providing the parameterized constructor as a convenience but it is not improper for a caller to be able to instantiate a HealthCheck with the "new" operator, then simply adding the parameterless constructor is acceptable.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow