c# - 代码生成器错误 : There is no entity type on DbContext

标签 c# entity-framework asp.net-core

我想创建简单的 ASP.NET Core 应用程序。但是当我尝试为我的模型生成 API Controller 时,出现以下错误: (屏幕截图显示了模型类和数据库上下文的代码,下面是 EntityBase 类的代码)

Setting up code scaffolding properties

Error

public abstract class EntityBase
{
    [Key]
    public int Id { get; set; }
    public DateTime Modified { get; set; }
    public DateTime Created { get; set; }

    public EntityBase()
    {
        Created = DateTime.Now;
        Modified = Created;
    }
}

最佳答案

遇到与标题相同的问题,但没有任何 key 或关系问题,我终于找到了解决这个问题的方法。特别是对于通过数据库优先方法创建的模型类的脚手架 Controller / View 。在您的 DbContext 类中,您必须采用 DbContextOptions<MyDb> 的类构造函数参数,出于某种原因,它不会在包管理器控制台(使用 ASPNETCORE 项目)中使用“Scaffold-DbContext”命令添加

public partial class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }
    public virtual DbSet<MyModel> MyModel { get; set; }
}

对于其他人也需要在 appsettings.json 文件中有连接字符串,并在文件 startup.cs 的 ConfigureServies 方法中添加以下代码:

se‌​rvices.AddDbContext<‌​MyDbContext>(opt‌​ions => options.UseSqlServer(Configuration.GetConnectionString("MyDbContection")));

关于c# - 代码生成器错误 : There is no entity type on DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37742851/

相关文章:

c# - 缺少必需的参数 '<PROVIDER>'。 ASP.NET Core 2.1.MAC中的Scaffold Dbcontext

json - JSON 对象内元素的 SwiftyJSON 顺序

entity-framework - Windows Azure 上的 EF 6 和空间类型 DbGeography

c# - 在 ASP.NET 中使用依赖注入(inject)和工厂模式传递服务

asp.net-core - 不同的基本路径取决于开发/生产环境

asp.net-core - Microsoft.Extensions.* 版本混淆

c# - 如何在.net core 2.2 的启动文件中注册polly?

C# .net 3.5 进程间通信验证子进程是否启动正常

c# - Entity Framework 中的分组和计数

c# - 在数组中查找升序重复对