Use MDF with entityframework Core

.net-core c# entity-framework-core scaffolding


I'm trying to figure out how to connect to an .mdf file using entityframework core. I found a resource on how to connect to one here However it doesn't seem to be working. I've made a var simple context using the Northwind dataset

public class Order
    public int OrderId { get; set; }
    public string CustomerID { get; set; }
    public int EmployeeID { get; set; }
    public DateTime OrderDate { get; set; }
    // etc.

public class NorthwindContext : DbContext
    public NorthwindContext(DbContextOptions options) : base(options) { }
    public DbSet<Order> Orders { get; set; }

I've created a test class to attempt to connect to the DB

public string NorthwindConnectionString = @"Data Source=.\SQLEXPRESS;
                      Integrated Security=True;
                      Connect Timeout=30;
                      User Instance=True";

public void TestMethod1()
    var optionsBuilder = new DbContextOptionsBuilder<NorthwindContext>();
    //I've also tried UseSqlLite()
    using (var context = new NorthwindContext(optionsBuilder.Options))
        var orders = context.Orders.ToList();

However when I attempt to run my tests I get an error

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


I've also tried moving my MDF to users folder and connect using this connection string:

Data Source=(LocalDB)\MSSQLLocalDB;DataBase=Northwind;Integrated Security=True;Connect Timeout=30"

However this doesn't seem to work as well, it throws an exception

SqlException: Cannot open database "Northwind" requested by the login. The login failed. Login failed for user 'MyUser'

Is there something wrong with my connection string?

I can't quite seem to figure out how to use an MDF with entityframework

6/19/2018 5:02:35 PM

Accepted Answer

I did some investigation, and it turns out that it was returning a bogus error because Northwind DB in built from SQL Server 2000, and I'm running SQL server 2016 so Instead I Created a Sample DB and used that as an MDF.

Now my connection string looks like so:

public static string MDF_Directory
        var directoryPath = AppDomain.CurrentDomain.BaseDirectory;
        return Path.GetFullPath(Path.Combine(directoryPath, "..//..//..//TestDB"));

public string astootConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB; " +
        "AttachDbFilename="+ MDF_Directory + "\\Astoot.mdf;" +
        " Integrated Security=True; Connect Timeout=30;";
6/20/2018 3:09:55 AM

Related Questions


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