将 MDF 与 entityframework 核心一起使用

Use MDF with entityframework Core

我正在尝试弄清楚如何使用 entityframework 核心连接到 .mdf 文件。我找到了有关如何连接到 here 的资源,但它似乎不起作用。我使用 Northwind 数据集

制作了一个 var 简单上下文
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; }
}

我已经创建了一个测试 class 来尝试连接到数据库

public string NorthwindConnectionString = @"Data Source=.\SQLEXPRESS;
                      AttachDbFilename=C:\source\Astoot\RestEzCore.Tests\TestDB\NORTHWND.MDF;
                      Integrated Security=True;
                      Connect Timeout=30;
                      User Instance=True";

[TestMethod]
public void TestMethod1()
{
    var optionsBuilder = new DbContextOptionsBuilder<NorthwindContext>();
    //I've also tried UseSqlLite()
    optionsBuilder.UseSqlServer(this.NorthwindConnectionString);
    using (var context = new NorthwindContext(optionsBuilder.Options))
    {
        var orders = context.Orders.ToList();
        Assert.IsTrue(orders.Any());
    }
}

然而,当我尝试 运行 我的测试时,出现错误

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

编辑

我还尝试将我的 MDF 移动到用户文件夹并使用此连接字符串进行连接:

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

然而这似乎并不奏效,它抛出一个异常

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

我的连接字符串有问题吗?

我似乎不太明白如何将 MDF 与 entityframework

一起使用

我做了一些调查,结果发现它返回了一个虚假错误,因为 Northwind DB 是从 SQL Server 2000 构建的,而我是 运行 SQL 服务器2016 年,所以我创建了一个示例数据库并将其用作 MDF。

现在我的连接字符串如下所示:

public static string MDF_Directory
{
    get
    {
        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;";