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
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:
The @
means you are using a verbatim string literal. You should not escape the \
between the server and instance name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With