Skip to main content
Entity Framework Core InMemory provider with ASP.NET Core

Entity Framework Core InMemory provider with ASP.NET Core

One of the new feature of EF Core is, Entity Framework Core InMemory provider. It’s a new db Provider which holds everything in memory. There is no database written to disk. This is useful for unit testing entity framework DB operations as InMemory storage behaves same as the actual database storage. So you don’t have to connect and query to actual database. So in this post, let’s see how to configure and use Entity Framework Core InMemory provider with an ASP.NET Core Application.

Entity Framework Core InMemory provider

Open VS 2015 and create an ASP.NET Core Web API application. If you are new to this, please read this post. So once the application is created, let’s first install the EF Core InMemory provider package. There are a couple of ways to do this.

  1. The new way is to open your Project.json file and look for dependencies section. Under dependencies add the following line and save your file.
    "Microsoft.EntityFrameworkCore.InMemory": "1.0.0"
    
  2. The old way is via Nuget Package Manager. Right click on Project and select Manage Nuget Packages. And within nuget package manager search for “EntityFrameworkCore.InMemory” and install the latest version.

    Adding EF Core InMemory Provider nuget package

  3. You can also use the package manager console to install this nuget package. Go to Tools->Nuget Package Manager and select Package Manager Console. On the console, execute following to install this nuget package.
    PM> Install-Package Microsoft.EntityFrameworkCore.InMemory -Version 1.0.0
    
  4. As of today the latest version is “1.0.0”.

Now, add a folder named “Model”. And inside this folder, add “Product.cs” (which is our entity) and “MyDbContext.cs” files. Following is the content of Product.cs

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Stock { get; set; }
}

And following is content of MyDbContext.cs file. As you can see, Product entity is added to it.

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
}

Now, let’s add a ProductController with some Get and Post methods to Controller folder. Post method adds Product object to context and stores it. Where Get method returns list of products and you can also get product by ID.

[Route("api/[controller]")]
public class ProductController : Controller
{
    private MyDbContext dbContext;

    public ProductController(MyDbContext dbContext)
    {
        this.dbContext = dbContext;
    }

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(this.dbContext.Products.ToList());
    }

    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        return Ok(this.dbContext.Products.FirstOrDefault(e => e.Id == id));
    }

    [HttpPost]
    public IActionResult Post([FromBody]Product product)
    {
        this.dbContext.Products.Add(product);
        this.dbContext.SaveChanges();
        return Created("Get", product);
    }
}

Finally, we need to configure InMemory db provider. Open Startup.cs and navigate to ConfigureServices method to configure it.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase());
}

Keep in mind that since it is InMemory provider, so everytime when you restart the application, there will be a fresh DB in memory. Now, let’s run the application. And when you send a get request to product controller, you should see an empty list as there is no data present in the dbcontext.

EFCore InMemory Provider API Sample - 1So now, let’s post some data to the controller. I am using Postman tool to post the data. You can also use fiddler or swagger. So send a post request to Product controller.

EFCore InMemory Provider API PostmanNow when we make a GET all products list, you can see the product we just created.

EFCore InMemory Provider API Sample - 2Again, if you create another post request and then make a GET all request, you should see all the products.

EFCore InMemory Provider API Sample - 3When Get by Id request is made, you will get that product information returned back.

EFCore InMemory Provider API Sample - 4

Here is a gif version of the complete flow.

Entity Framework Core In Memory provider with ASP.NET CoreOnce you stop the application, all the information present in InMemory provider is gone. Hope you get the idea of Entity Framework Core InMemory provider.

Summary

Entity Framework Core InMemory provider is a great addition to EF Core. It is quite handy for unit testing and can save your time while testing EF db operations. Thank you for reading and I hope it helped you. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

Leave a Reply

Your email address will not be published. Required fields are marked *

nineteen + nineteen =