Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to localdb from Entity Framework Core 1.x via a .Net Core Console Application

How can I use Entity Framework Core 1.x from a .NET Core 1.x Console Application inside of Visual Studio? I've tried the workflow and commands I'm used to from ASP.NET MVC Core 1.x development and I'm experiencing a connection error to the localdb.

How is working with localdb in a Console app different from working in an ASP.NET MVC Core 1.x app?

Background

Having successfully used ASP.NET MVC Core 1.x and Entity Framework Core 1.x several times, I needed to create a simple .NET Core Console app to do some grunt work (load XML into a new database creating tables that loosely match the structure of the XML).

I used NuGet to install

  • Microsoft.EntityFrameworkCore.Design (1.1.2)
  • Microsoft.EntityFrameworkCore.SqlServer (1.1.2)
  • Microsoft.EntityFrameworkCore.Tools (1.1.1)

I created a DbContext with DbSets. I added an OnConfiguring() method and hard coded the connection string like I found in a code example online. My DbContext looks like this:

public class ApplicationDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\\mssqllocaldb;Database=MyXmlExport;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

    public DbSet<Author> Authors { get; set; }
    public DbSet<Thread> Threads { get; set; }
    public DbSet<Post> Posts { get; set; }
}

I grabbed the connection string from a working ASP.NET MVC Core 1.x application's appsettings.json, changing the database name to something simple ("MyXmlExport").

I was able to create an initial migration.

When I attempted to use the workflow I'm used to, namely calling:

update-database

I get the following error:

"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Specified LocalDB instance name is invalid."

I can connect to the localdb instance via Sql Server Object Explorer. I tried creating the MyXmlExport database manually, hoping that would reduce at least one potential issue. But it seems that Visual Studio's tooling can't access the database when used in the context of a Console application.

Full error stack:

Full error stack

like image 698
Bob Tabor Avatar asked Aug 03 '17 15:08

Bob Tabor


1 Answers

The @ means you are using a verbatim string literal. You should not escape the \ between the server and instance name.

like image 62
roryWoods Avatar answered Sep 28 '22 09:09

roryWoods