'PostgreSql and EntityFramework Unable to create an object of type
when I am trying to use this command dotnet ef migrations add InitialCreate
I am getting error like : Unable to create an object of type 'BlogDbContext'. For the different patterns supported at design time etc...
Also I tried this(dotnet tool install --global dotnet-ef
) solution but does not worked for me.
My BlogDbContext code :
public class BlogDbContext : DbContext
{
public BlogDbContext(DbContextOptions<BlogDbContext> options) : base (options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Blog>();
}
}
Also I added my App class. App class contains my Run function.
public class App
{
public App()
{
}
public void Run()
{
var services = new ServiceCollection();
var connstr = "Host=localhost;Database=blog;Port=5432;Username=postgres;Password=mysecretpassword";
services.AddDbContext<BlogDbContext>(x => x.UseNpgsql(connstr).UseSnakeCaseNamingConvention());
var provider = services.BuildServiceProvider();
using (var ctx = provider.GetService<BlogDbContext>())
{
ctx.Add(new Blog());
ctx.SaveChanges();
}
}
}
Solution 1:[1]
Add a constructor to your BlogDbContext and it will fix the issue. I found this issue and also add a feedback at Microsoft doc site.
public class BlogDbContext : DbContext
{
// add this method
public BlogDbContext()
{
}
public BlogDbContext(DbContextOptions<BlogDbContext> options) : base (options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Blog>();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jason |