Thursday, September 8, 2022
HomeITHow you can use EF Core as an in-memory database in ASP.NET...

How you can use EF Core as an in-memory database in ASP.NET Core 6


There are lots of explanation why you would possibly need to use an in-memory database when engaged on ASP.NET Core 6 internet functions. Possibly you’re creating a brand new characteristic and also you need to check it with out affecting your manufacturing database. Or maybe you need a fast method to prototype one thing with out establishing an entire new database.

Entity Framework Core, or EF Core for brief, simplifies information entry in .NET Core functions and means that you can write code to carry out CRUD (create, learn, replace, delete) operations with out straight interacting with the underlying database supplier. The EF Core In-Reminiscence Database Supplier permits us to make use of EF Core with an in-memory database for testing.

The EF Core In-Reminiscence Database Supplier lets us retailer and retrieve information to and from reminiscence in .NET Core 6 functions. Simply keep in mind that this supplier was designed for testing functions solely.

This text discusses how we are able to use EF Core with an in-memory database in an ASP.NET Core 6 software. To work with the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your system. In case you don’t have already got a duplicate, you possibly can obtain Visible Studio 2022 right here.

Create an ASP.NET Core Internet API challenge in Visible Studio 2022

First off, let’s create an ASP.NET Core challenge in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core 6 Internet API challenge in Visible Studio 2022:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “ASP.NET Core Internet API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window, specify the title and placement for the brand new challenge.
  6. Optionally verify the “Place answer and challenge in the identical listing” verify field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Further Info” window proven subsequent, choose .NET 6.0 because the goal framework from the drop-down listing on the prime. Go away the “Authentication Sort” set to “None” (default).
  9. Be sure that the verify containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
  10. Click on Create.

We’ll use this ASP.NET Core 6 Internet API challenge to work with EF Core and an in-memory database within the subsequent sections of this text.

What’s EF Core? When ought to we use it?

EF Core is a light-weight, open-source, extensible ORM (Object Relational Mapper) that helps a number of database suppliers together with SQLite, MySQL, PostgreSQL, and Microsoft SQL Server. (You’ll discover a full listing of EF Core suppliers right here.) And, as we’ve famous, EF Core helps storing and retrieving information to and from reminiscence utilizing its In-Reminiscence Database Supplier.

EF Core additionally helps LINQ (Language Built-in Question), which makes it simpler to jot down queries towards the information in your database. It is because LINQ means that you can write queries straight in C# as an alternative of SQL or another question language.

The power to retailer and retrieve information in reminiscence utilizing the EF Core In-Reminiscence Database Supplier is particularly well-suited for testing apps or for constructing functions that have to retailer information quickly. And since an in-memory database is each quick and quick to arrange, it is vitally helpful to make use of one for unit testing.

What’s an in-memory database?

An in-memory database is a database that resides in risky reminiscence as an alternative of on a bodily disk. Naturally, reads and writes for an in-memory database are many occasions sooner than for a disk-based database, as a result of the appliance needn’t look forward to the information to be bodily written to or learn from the disk. Studying and writing information saved on a bodily disk is a resource-intensive operation.

In-memory databases are sometimes used for caching functions, as they’ll maintain a duplicate of often-used information in reminiscence for fast entry. You may as well reap the benefits of in-memory databases to retailer transient information, i.e., information that doesn’t must be continued to the disk.

There are additionally some notable downsides to utilizing an in-memory database, although these apply to manufacturing use and never our testing state of affairs. One among these is that when you’re utilizing an in-memory database, the information won’t be continued when the appliance stops operating (except you’re taking steps to persist it). Which means that if the appliance crashes, all the information residing within the in-memory database might be misplaced.

One other draw back is that an in-memory database makes use of way more reminiscence in comparison with a standard database that resides on a bodily disk (and reminiscence is much costlier than disk storage). Because of this, an in-memory database might not be appropriate for functions that take care of huge quantities of information. However once more, these downsides don’t actually apply to utilizing an in-memory database for testing.

Utilizing an in-memory database in ASP.NET Core 6

On this part we’ll study how we are able to use an in-memory database to retailer and retrieve information in an ASP.NET Core 6 software. We’ll comply with these steps to create and use an in-memory database in ASP.NET Core 6:

  1. Set up the EF Core InMemory NuGet bundle
  2. Create a brand new customized DbContext class
  3. Create the mannequin lessons
  4. Create the Repository class
  5. Add the Repository as a service to the container
  6. Create a brand new controller
  7. Use dependency injection within the controller to entry the Repository occasion
  8. Execute the appliance

Let’s get began!

Set up the EF Core InMemory NuGet bundle

To leverage the in-memory capabilities of EF Core in your software, it’s best to add the Microsoft.EntityFrameworkCore.InMemory bundle to your challenge. To do that, choose the challenge within the Answer Explorer window, then right-click and choose “Handle NuGet Packages.” Within the NuGet Package deal Supervisor window, seek for the Microsoft.EntityFrameworkCore.InMemory bundle and set up it.

Alternatively, you possibly can set up the bundle through the NuGet Package deal Supervisor console by coming into the command proven under.

PM> Set up-Package deal Microsoft.EntityFrameworkCore.InMemory

Create a customized DbContext class in ASP.NET Core 6

In EF Core, the DbContext is utilized by the appliance to work together with the underlying database. Earlier than we proceed, let’s create a customized DbContext class that we’ll use to increase the DbContext class of the EF Core framework.

utilizing EFCoreInMemoryDbDemo.Fashions;
utilizing Microsoft.EntityFrameworkCore;
namespace EFCoreInMemoryDbDemo
{
    public class ApiContext : DbContext
    {
        protected override void OnConfiguring
       (DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseInMemoryDatabase(databaseName: "AuthorDb");
        }
        public DbSet<Writer> Authors { get; set; }
        public DbSet<Guide> Books { get; set; }
    }
}

Observe how we have now specified the title of the in-memory database within the OnConfiguring methodology.

Create mannequin lessons in ASP.NET Core 6

We’ll use two easy mannequin lessons for working with information on this software. These mannequin lessons are Writer and Guide. Create a brand new .cs file named Writer.cs and enter the next code:

    public class Writer
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Record<Guide> Books { get; set; }
    }

Create one other .cs file named Guide.cs and provides it the next code:

    public class Guide
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public Writer Writer { get; set; }
    }

Create a Repository class in ASP.NET Core 6

Create an interface named IAuthorRepository in a file having the identical title with a .cs extension and write the next code in there:

public interface IAuthorRepository
{
    public Record<Writer> GetAuthors();
}

The AuthorRepository class implements the members of the IAuthorRepository interface as proven within the code itemizing given under.

utilizing EFCoreInMemoryDbDemo.Fashions;
utilizing Microsoft.EntityFrameworkCore;
namespace EFCoreInMemoryDbDemo
{
    public class AuthorRepository : IAuthorRepository
    {
        public AuthorRepository()
        {
            utilizing (var context = new ApiContext())
            {
                var authors = new Record<Writer>
                {
                new Writer
                {
                    FirstName ="Joydip",
                    LastName ="Kanjilal",
                       Books = new Record<Guide>()
                    {
                        new Guide { Title = "Mastering C# 8.0"},
                        new Guide { Title = "Entity Framework Tutorial"},
                        new Guide { Title = "ASP.NET 4.0 Programming"}
                    }
                },
                new Writer
                {
                    FirstName ="Yashavanth",
                    LastName ="Kanetkar",
                    Books = new Record<Guide>()
                    {
                        new Guide { Title = "Allow us to C"},
                        new Guide { Title = "Allow us to C++"},
                        new Guide { Title = "Allow us to C#"}
                    }
                }
                };
                context.Authors.AddRange(authors);
                context.SaveChanges();
            }
        }
        public Record<Writer> GetAuthors()
        {
            utilizing (var context = new ApiContext())
            {
                var listing = context.Authors
                    .Embody(a => a.Books)
                    .ToList();
                return listing;
            }
        }
    }
}

Observe how the customized DbContext we created earlier is used within the AuthorRepository class to retailer and retrieve information to and from the in-memory database.

Add the Repository service to the companies container in ASP.NET Core 6

To make use of dependency injection in your controllers or different lessons in your challenge, it’s essential to add the companies to the dependency injection container.

Add the next line of code within the Program.cs file so as to add the AuthorRepository service to the container.

builder.Providers.AddScoped<IAuthorRepository, AuthorRepository>();

Right here is the whole supply code of the Program.cs file in your reference:

utilizing EFCoreInMemoryDbDemo;
var builder = WebApplication.CreateBuilder(args);
builder.Providers.AddScoped<IAuthorRepository, AuthorRepository>();
builder.Providers.AddControllers();
builder.Providers.AddEndpointsApiExplorer();
builder.Providers.AddSwaggerGen();
var app = builder.Construct();
if (app.Setting.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Create a Internet API controller in ASP.NET Core 6

To date so good. Now, right-click on the Controllers answer folder, click on “Add -> Controller…”, and create a brand new API controller in your challenge. Identify the controller AuthorController and change the default generated code with the next:

utilizing EFCoreInMemoryDbDemo.Fashions;
utilizing Microsoft.AspNetCore.Mvc;
namespace EFCoreInMemoryDbDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorController : ControllerBase
    {
        readonly IAuthorRepository _authorRepository;
        public AuthorController(IAuthorRepository authorRepository)
        {
            _authorRepository = authorRepository;
        }
        [HttpGet]
        public ActionResult<Record<Writer>> Get()
        {
            return Okay(_authorRepository.GetAuthors());
        }
    }
}

Observe how dependency injection has been used to inject an occasion of kind IAuthorRepository within the constructor of the AuthorController class. The HttpGet motion methodology of the AuthorController class calls the GetAuthors methodology of the AuthorRepository class and returns an inventory of authors.

Lastly, once you execute the appliance and hit the HttpGet endpoint of the AuthorController utilizing Postman, it’s best to see the output as proven in Determine 1 under.

ef core in memory database 01 IDG

Determine 1. Testing our easy in-memory database created with ASP.NET Core 6 and EF Core.

This was a minimalistic implementation of an ASP.NET Core 6 internet software with the first intent of displaying you the right way to work with an in-memory database utilizing EF Core. It’s best to write your individual customized code to generate the Ids for each of the mannequin lessons. Moreover, you would possibly reap the benefits of unit checks to check the endpoints in your software. As you would possibly count on, unit checks that leverage the EF Core In-Reminiscence Database Supplier will run fairly quick.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments