受欢迎的博客标签

InMemory Database in ASP.NET Core

Published

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.

InMemory is not a relational database.EF Core database providers do not have to be relational databases. InMemory is designed to be a general purpose database for testing, and is not designed to mimic a relational 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 2019 and create an ASP.NET Core Web API application. If you are new to this, please read this post.

Step 1.Install-Package Microsoft.EntityFrameworkCore.InMemory

To use the .UseInMemoryDatabase() extension method, reference the NuGet package Microsoft.EntityFrameworkCore.InMemory.

Install-Package Microsoft.EntityFrameworkCore.InMemory

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. 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" 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.

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 As of today the latest version is “1.0.0”.

Step 2:write a DBContext

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);   

  } }

Step 3:Configure the DBContext in Startup.cs

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. So 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.

Now when we make a GET all products list, you can see the product we just created. Again, if you create another post request and then make a GET all request, you should see all the products. When Get by Id request is made, you will get that product information returned back.

 Once you stop the application, all the information present in InMemory provider is gone. Hope you get the idea of Entity Framework Core InMemory provider..

 

Using EF Core's InMemory Provider To Store A "Database" In Memory

This example project is used in this blog posts on github

https://github.com/dotnet/efcore

 Create a .NET Core console app that performs data access against a SQLite database using Entity Framework Core