如何将 DbContext 添加到 MSTest 项目?

Ril*_*n42 1 c# mstest dbcontext

我试图测试一些使用实体框架的代码,但我无法弄清楚如何从单独的 MSTest 项目中引用 EF 上下文类。两个项目都在同一个解决方案中。

无法将 lambda 表达式转换为类型“DbContextOptions”,因为它不是委托类型

在我的测试用例中:

[TestClass]
public class GreenCardUserTest
{
    [TestMethod]
    public void TestAddUser()
    {
        // REFERENCE TO OTHER PROJECT. WORKS FINE
        AppUserViewModel a = new AppUserViewModel();

        //LIKELY INCORRECT attempt to duplicate code from Startup.cs in other project
        using (GreenCardContext _gc = new GreenCardContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection"))))
        {
            new GCLandingUserModel().AddUser(a,_gc);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

摘自主项目 Startup.cs(工作正常):

services.AddDbContext<GreenCardContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
Run Code Online (Sandbox Code Playgroud)

aqt*_*fan 5

我建议使用 InMemoryDatabase:

在您的测试类中,使用 [TestInitialize] 来设置您的虚拟数据库:

[TestClass]
public class GreenCardUserTest
{
    private readonly context;

    [TestInitialize]
    public Setup()
    {
        DbContextOptions<GreenCardContext> options;
        var builder = new DbContextOptionsBuilder<GreenCardContext>();
        builder.UseInMemoryDatabase();
        var options = builder.Options;
        context = new GreenCardContext(options);
    }

    [TestMethod]
    public void TestAddUser()
    {
        // user context here...
    }
}
Run Code Online (Sandbox Code Playgroud)