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)
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;
}
}
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:
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbContection")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With