In any system, we need master data which is not going to be changed frequently but is mandatory to maintain, in order to run the system smoothly. For example, in an E-commerce website, the product category is required frequently while traversing the site or referring to the product. And such data is not modified often. Now, assume that whenever the category is required, you fetch it from the database and pass it to the site. Well, that becomes a more expensive call. So, as a partial solution, we can keep it in memory so that we can avoid the database call. Microsoft has provided InMemory database with Entity Framework Core.
Let’s see its step by step implementation in .NET Core Web API.
Open Visual Studio and create a new project. Select the API and click the OK button.
In order to use InMemory database, we need to install a NuGet package, i.e., Microsoft.EntityFrameworkCore.InMemory.
Create a model for Category. This model will be having fields like Id and CategoryName. Please make sure that the Id column is added in each model.
- namespace EFCoreInMemory
- {
- public class Category
- {
- public int Id { get; set; }
- public string CategoryName { get; set; }
- }
- }
Create a class called ApiContext which inherits from DbContext.
Declare the public property of type DbSet for Category.
From the parameterized constructor, you can load categories. This data can be loaded from the database, but for demo purposes, I have added hardcoded ones.
Also, create a GetCategories method which returns the list of categories from DbSet.
- using Microsoft.EntityFrameworkCore;
- using System.Collections.Generic;
- using System.Linq;
-
- namespace EFCoreInMemory
- {
- public class ApiContext : DbContext
- {
- public DbSet<Category> Categories { get; set; }
-
- public ApiContext(DbContextOptions options) : base(options)
- {
- LoadCategories();
- }
-
- public void LoadCategories()
- {
- Category category = new Category() { CategoryName = "Category1" };
- Categories.Add(category);
- category = new Category() { CategoryName = "Category2" };
- Categories.Add(category);
- }
-
- public List<Category> GetCategories()
- {
- return Categories.Local.ToList<Category>();
- }
- }
- }
Inject ApiContext to the CategoryController via constructor.
Create a GET method which will call GetCategories of ApiContext and return the data.
- using Microsoft.AspNetCore.Mvc;
- using System.Collections.Generic;
- using System.Threading.Tasks;
-
- namespace EFCoreInMemory.Controllers
- {
- [Route("api/Category")]
- public class CategoryController : Controller
- {
- private readonly ApiContext apiContext;
-
- public CategoryController(ApiContext apiContext)
- {
- this.apiContext = apiContext;
- }
-
-
- [HttpGet]
- public async Task<IActionResult> Get()
- {
- List<Category> categories = apiContext.GetCategories();
- return Ok(categories);
- }
- }
- }
Configure ApiContext in the startup class with the option UseInMemoryDatabase.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace EFCoreInMemory
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApiContext>(opt => opt.UseInMemoryDatabase());
- services.AddScoped<ApiContext>();
-
- services.AddMvc();
- }
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseMvc();
- }
- }
- }
Now, run the application and you will be able to see all the added categories. Here, if you observe the result closely, you can see that the Id is added like 1 and 2. But while loading the categories, we have set the CategoryName only; then how it will be added? So, if you remember, at the time of designing a model, I mentioned you should make sure the Id column is added. An InMemory database internally keeps Id and behaves like AutoIncrement feature of SQL. For example, when you add 10 categories the first time, then the Id is given from 1 to 10. Now, if you remove any of the categories in between 1 to 10, (let’s say we are removing category 6) and again you will add the same category, it will get a new Id assigned. (Category Id 6 will be 11 now). This means once you remove the row, Id cannot be reset automatically.
You can download the sample code from here.