Is there an in-memory provider for Entity Framework?

前端 未结 8 2298
情书的邮戳
情书的邮戳 2020-12-05 22:42

I am unit testing code written against the ADO .NET Entity Framework. I would like to populate an in-memory database with rows, and make sure that my code retrieves them pro

相关标签:
8条回答
  • 2020-12-05 23:07

    In EF Core there are two main options for doing this:

    1. SQLite in-memory mode allows you to write efficient tests against a provider that behaves like a relational database.
    2. The InMemory provider is a lightweight provider that has minimal dependencies, but does not always behave like a relational database

    I am using SQLite and it supports all queries, that I need to do with Azure SQL production database.

    0 讨论(0)
  • 2020-12-05 23:08

    You could try SQL Server Compact but it has some quite wild limitations:

    • SQL Server Compact does not support SKIP expressions in paging queries when it is used with the Entity Framework
    • SQL Server Compact does not support entities with server-generated keys or values when it is used with the Entity Framework
    • No outer joins, collate, modulo on floats, aggregates
    0 讨论(0)
  • 2020-12-05 23:14

    Yes, there is at least one such provider - SQLite. I have used it a bit and it works. Also you can try SQL Server Compact. It's an embeded database and has EF providers too.
    Edit:
    SQLite has support for in-memory databases (link1). All you need is to specify a connection string like: "Data Source=:memory:;Version=3;New=True;". If you need in an example you may look at SharpArchitecture.

    0 讨论(0)
  • 2020-12-05 23:22

    I am not familiar with Entity Framework and the ObjectQuery class but if the Include method is virtual you can mock it like this:

    // Arrange
    var customerSourceStub = MockRepository.GenerateStub<ObjectQuery<Customer>>();
    var customers = new Customer[] 
    {
        // Populate your customers as if they were coming from DB
    };
    customerSourceStub
        .Stub(x => x.Include("Order"))
        .Return(customers);
    var sut = new CustomerService(customerSourceStub);
    
    // Act
    var actual = sut.GetCustomerById(5);
    
    // Assert
    Assert.IsNotNull(actual);
    Assert.AreEqual(5, actual.Id);
    
    0 讨论(0)
  • 2020-12-05 23:23

    There is not currently a in memory provider for EF, but if you take a look at Highway.Data it has a base abstraction interface and an InMemoryDataContext.

    Testing Data Access and EF with Highway.Data

    0 讨论(0)
  • 2020-12-05 23:28

    An InMemory provider is included in EF7 (pre-release).

    You can use either the NuGet package, or read about it in the EF repo on GitHub (view source).

    0 讨论(0)
提交回复
热议问题