Isolate Sample with an InMemory Database Provider
Environment
Product | Progress® Telerik® UI for ASP.NET MVC |
Description
Providing a runnable ASP.NET MVC application plays a crucial role during support communication. However, more often than not, isolating a sample by stripping out the database layer inevitably opposes difficulties depending on the application's proportions
Solution
A potential way to isolate a runnable sample while preserving the database layer is to use a InMemoryDatabase Provider
.
Using this tool, you can configure the application by following the next steps:
-
Install the
Microsoft.EntityFrameworkCore.InMemory
package. -
Create a new
InMemoryDatabase
context class.
public class InMemoryDbContext: DbContext
{
public InMemoryDbContext(DbContextOptions<InMemoryDbContext> options)
: base(options)
{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
public DbSet<EmployeeViewModel> Employees { get; set; }
}
- Within the minimal hosting model of the application, register the
InMemoryDatabase
context by explicitly using theUseInMemoryDatabase()
extension method.
builder.Services.AddDbContext<InMemoryDbContext>(options =>
options.UseInMemoryDatabase("TelerikCoreDb")
);
- (Optional) Create a seeder, so that you can mock data onto the
InMemoryDatabase
context.
public class DataSeeder
{
public static void SeedData(InMemoryDbContext dbContext)
{
if (dbContext.Employees.Any())
{
return;
}
var employees = new List<EmployeeViewModel>
{
...
};
dbContext.Employees.AddRange(employees);
dbContext.SaveChanges();
}
}
-
Seed the data within the minimal hosting model.
C#using (var serviceScope = app.Services.CreateScope()) { var inMemoryContext = serviceScope.ServiceProvider.GetRequiredService<InMemoryDbContext>(); // Gather a reference of the InMemoryDbContext. DataSeeder.SeedData(inMemoryContext); // Call the previously created DataSeeder. }
-
Inject the newly created
InMemoryDatabase
context within the desired controller.C#public class RemoteBindingController : Controller { private readonly InMemoryDbContext _dbContext; public RemoteBindingController(InMemoryDbContext dbContext) { _dbContext = dbContext; } public IActionResult GetEmployees() { var employees = _dbContext.Employees.ToList(); return Json(employees); } }
To see a fully runnable sample, refer to the following GitHub Example.