.net core Migration error: Unable to create an object of type 'DataContext'

Viewed 2089

Im trying to set up a dotnet backend with separate projects, i have the API project(which is a webapi) as the main project, then i have the persistance project that contains the DataContext class.

DataContext.cs:

using Domain;
using Microsoft.EntityFrameworkCore;

namespace Persistence
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {

        }
        public DbSet<Book> Books { get; set; }
    }
}

And i am injecting the DataContext into the configuration services in The startup file:

   public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(opt =>
            {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddControllers();
        }

then when i try adding a migration using this command:

dotnet ef migrations add InitialCreate -s API -p Persistence    

It gives me that error.

Please any idea why this is happening ?

2 Answers

first of all check your connection string in appsettings.json and after that run this commands for migrations

dotnet ef migrations add 1

then

dotnet ef migrations update

and if didnt work check you ef core package from *.csproject

try to add an empty constructor:

public DataContext(){}

Related