EF Core migration with SQLite database: unable to create object of type

c# entity-framework entity-framework-core

Question

I'm trying to make an initial migration of SQLite database with Entity Framework Core.

My solution consists of two projects: Console Application and Class Library (that contains DbContext and all models).

DbContext looks like that:

public class SQLite_DbContext : DbContext
{
    public DbSet<DeviceRepresentation> Devices { get; set; }
    public DbSet<FileInfoDatabaseRepresentation> Files { get; set; }

    public SQLite_DbContext(DbContextOptions<SQLite_DbContext> options)
        : base(options)
    {
    }
}

Being in class library (where I keep my DbContext), I'm trying to create migration:

dotnet ef migrations add InitialCreate

As a result, dotnet cli returns an error:

Unable to create an object of type 'SQLite_DbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Can you see what could be a problem here?

1
1
10/7/2019 2:37:24 PM

Popular Answer

I've probably found the solution. There is a nice explanation of what's happening under-the-hood while generating migrations in docs [here].

In my case, according to documentation, EF Core Tools are trying to create an instance of SQLite_DbContext passing no parameters to the constructor. Such constructor wasn't present in my code, because there is only one taking one parameter (options). That's the reason why it was "unable to create an object". When I removed my custom constructor from code, it started generating migrations properly.

Alternatively, as I see, there is also an option to take control of how DbContext is being created. There is possibility to create "factory" which EF tools will use to generate an instance of this class:

public class SQLite_DbContextFactory : IDesignTimeDbContextFactory<SQLite_DbContext>
    {
        public SQLite_DbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<SQLite_DbContext>();
            optionsBuilder.UseSqlite("Data Source=blog.db");

            return new SQLite_DbContext(optionsBuilder.Options);
        }
    }
4
10/7/2019 6:34:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow