.NET Core - 添加Scaffolded Item"创建DbContext以获取模型时出现错误"

时间:2016-10-31 17:20:53

标签: c# .net

每当我尝试为项目创建一个新的脚手架项目时,都会收到一条错误说明

There was an error creating the DbContect instance to get the model No Parameterless constructor defined for this object.

我试图重建我的项目,并且我之前已经成功生成脚手架,但是出于某种原因,这样做现在我还没有取得任何成功。自从我上次添加一个新的脚手架项目以来,我的上下文类没有做任何改动。

我试图在我的模型中创建一个空构造函数,但它仍然会抛出相同的错误。下面你会找到我的模型代码,我试图用脚手架和我的上下文。

namespace HRIAT.Models
{

    public class Credential
    {

        public Credential() { }

        public int ID { get; set; }
        public string credentialName { get; set; }
        public FundingSource credentialFundingSource { get; set; }
        public string credentialType { get; set; }
        public float credentialCost { get; set; }

        public ICollection<Employee> ec { get; set; }


    }
}

上下文类:

namespace HRIAT.Models
{
    public class HRIATContext : DbContext
    {
        public HRIATContext(DbContextOptions<HRIATContext> options)
            : base(options)
        {
        }


        public DbSet<FundingSource> FundingSource { get; set; }

        public DbSet<Credential> Credential { get; set; }

        public DbSet<Employee> Employee { get; set; }

        public DbSet<EmployeesCredentials> EmployeeCredential { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<EmployeesCredentials>().HasKey(c => new { c.CredentialID, c.employeeNum });
        }

        public DbSet<Position> Positions { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Location> Locations { get; set; }


    }
}

1 个答案:

答案 0 :(得分:0)

如果项目的实体不包含空构造函数,则会出现此错误。 EntityFramework需要空构造函数来实例化实体并映射模式的属性。

如果需要保护实体类,请使用受保护的构造函数,例如:

public class Person 
{
    public string Name { get; private set; }

    public Person(string name)
    {
        Name = name;
    }

    protected Person() { }

}