Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code generator error: There is no entity type on DbContext

I want to create simple ASP.NET Core App. But when I'm trying to generate API Controller for my model I'm getting following error: (Screen shots presents code for model class and db context, below is code for EntityBase class)

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;
    }
}
like image 582
Artur Michajluk Avatar asked Jun 10 '16 07:06

Artur Michajluk


1 Answers

Having had the same issue as the title mentioned, but without any key or relationship issue, I finally found a solution to this issue. Particularly with scaffolding controllers/views from model classes that were created by a database-first approach. In your DbContext class you MUST HAVE the class constructor that takes the DbContextOptions<MyDb> parameter, which for some reason does not get added with the 'Scaffold-DbContext' command in the Package Manager Console (with an ASPNETCORE project)

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

For others as well there needs to be the connection string in the appsettings.json file, and the following code in the ConfigureServies method of the file startup.cs add:

se‌​rvices.AddDbContext<‌​MyDbContext>(opt‌​ions => options.UseSqlServer(Configuration.GetConnectionString("MyDbContection")));
like image 53
Edward Avatar answered Nov 13 '22 22:11

Edward