ASP.NET 5 Console Application (package) - How to create DBContext from connection string?

.net-core asp.net-core c# console-application entity-framework-core

Question

I'm trying to create DBContext from connection string on .net core. This used to work with .net 4.5:

public class MyContext : DbContext
{
   internal MYContext(string connectionString) : base(connectionString){}
}

Now I'm getting error that the base class (DBContext) doesn't have constructor that accepts string.

Any ideas?

Accepted Answer

DbContext doesn't have this constructor anymore. You can specify the connection string in OnConfiguring method overload:

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {         
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");

    }
}

https://ef.readthedocs.org/en/latest/getting-started/full-dotnet/new-db.html

UseSqlServer is an extension method for DbContextOptionsBuilder



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