DbContext Not Found or A relational store has been configured without specifying either the DbConnection or connection string to use

asp.net-core asp.net-core-mvc entity-framework-core

Question

when using Entity Framework Commands ("7.0.0-beta1").

when running

k ef migration add InitialCreate

i'm getting errors.

[Solution]

i try to move my Class File (where DbContext is created) to main project from separate class library and everything working as expected.

so the real problem is when using DbContext in separate Class Library.

my dbcontext file

public class DbTables : DbContext
{

    public DbSet<class_name> class_name_alias { get; set; }

    private static bool _created = false;

    public DbTables()
    {
        if (_created)
        {
            Database.AsRelational().ApplyMigrations();
            _created = true;
        }
    }

    protected override void OnConfiguring(DbContextOptions options)
    {
        options.UseSqlServer(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=app_db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

}

Accepted Answer

If you create a DBContext in a class library, to create migration you have to declare the ef command in the project.json of this class library. and run the k ef commmand for this project.

{
    "version": "1.0.0-*",
    "dependencies": {
        "EntityFramework.SqlServer": "7.0.0-beta1",
        "EntityFramework.Commands": "7.0.0-beta1" 
    },
    "commands": {
        "ef": "EntityFramework.Commands"
    },
    "frameworks" : {
        "aspnet50" : { 
            "dependencies": {
            }
        },
        "aspnetcore50" : { 
            "dependencies": {
                "System.Runtime": "4.0.20-beta-22231"
            }
        }
    }
}

You must override the on OnConfiguring method to set up a connection string

protected override void OnConfiguring(DbContextOptions options)
{
    options.UseSqlServer(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=app_db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why