NUnit中DbContextOptionsBuilder的数据类型

时间:2018-10-15 05:46:50

标签: c# entity-framework asp.net-core nunit moq

我正在尝试查找DbContextOptionsBuilder的数据类型。

我有一个Entity Framework DBContext文件。我用NUnit设置了一个InMemory数据库。我如何在不使用var的情况下进行设置?我知道最好的做法是为每个测试建立一个干净的数据库,但是只是尝试学习,并为多个测试建立一个数据库。

电子DBContext文件

public partial class ElectronicsContext : DbContext
{
    public ElectronicsContext()
    {
    }

    public ElectronicsContext(DbContextOptions<ElectronicsContext> options)
        : base(options)
    {
    }

public virtual DbSet<Product> Product { get; set; }
public virtual DbSet<ProductCategory> ProductCategory { get; set; }

NUnit测试

public class TestClass
{

[SetUp]
public void TestProducts()
{

   // This Works
   // var context = new DbContextOptionsBuilder<ElectronicsContext>()
   //     .UseInMemoryDatabase(databaseName: "ProductsTest")
   //     .Options;

   // This does not work
    DbContextOptionsBuilder<ElectronicsContext> context = new DbContextOptionsBuilder<ElectronicsContext>()
        .UseInMemoryDatabase(databaseName: "ProductsTest")
        .Options;

运行此命令时:我在下面收到错误消息,但是它以其他方式Moq and setting up DB Context

起作用
    [Test]
    public void TestProducts()
    {
        DbContextOptionsBuilder<ElectronicsContext> context = new DbContextOptionsBuilder<ElectronicsContext>()

        context.Product.Add(new Product { ProductId = 1, ProductName = "TV", ProductDescription = "TV testing", ImageLocation = "test" });
        context.SaveChanges();

Error: 'DbContextOptionsBuilder<ElectronicsContext>' does not contain a definition for 'Product' and no accessible extension method 'Product' accepting a first argument of type 'DbContextOptionsBuilder<ElectronicsContext>' could be found (are you missing a using directive or an assembly reference?) 

1 个答案:

答案 0 :(得分:0)

问题是您正在尝试将类型DbContextOptions的对象分配给类型DbContextOptionsBuilder<ElectronicsContext>的变量。查看作业的最后一行,您有.Options;

// This does not work
DbContextOptionsBuilder<ElectronicsContext> context = new DbContextOptionsBuilder<ElectronicsContext>()
    .UseInMemoryDatabase(databaseName: "ProductsTest")
    .Options;

由于C#是静态/强类型的,因此不允许使用,编译器会抱怨它。但是,从c#3.0 var开始引入。它只是语法糖,这是该语言提供的快捷方式,可以减少在某些常见情况下必须编写的代码量。

您的示例是鼓励您使用var,比较行长和可读性的示例之一。

没有var

DbContextOptionsBuilder<ElectronicsContext> context = new DbContextOptionsBuilder<ElectronicsContext>()

使用var

var context = new DbContextOptionsBuilder<ElectronicsContext>()