A .NET solution for implementing dynamic schema switching in Entity Framework Core applications, perfect for multi-tenant architectures where schema isolation is required.
- Dynamic schema switching at runtime
- Middleware support for schema resolution
- Action filters for schema validation
- Global parameter service for schema management
- Support for header-based and query parameter-based schema selection
- Thread-safe schema context handling
- .NET 8.0 or later
- SQL Server (or compatible database)
- Entity Framework Core 8.0 or later
- Clone the repository:
git clone https://github.com/shady78/MultiSchema.DbContext.Dynamic.git- Add the required NuGet packages:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer- Configure your connection string in
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Your_Connection_String_Here"
}
}builder.Services.AddScoped<IGlobalParameterService, GlobalParameterService>();
builder.Services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
{
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
);
options.EnableServiceProviderCaching(false);
});app.UseMiddleware<GlobalParameterMiddleware>();[HttpGet]
public IActionResult GetAll([FromQuery] string schema)
{
_parameterService.SetSchemaName(schema);
using var scope = _serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var results = context.YourEntity.ToList();
return Ok(results);
}The solution implements a One-layer architecture:
GlobalParameterMiddleware: Extracts schema from request headersGlobalParameterService: Manages schema stateGlobalParameterActionFilter: Validates schema parametersApplicationDbContext: Implements dynamic schema switching
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details
- Entity Framework Core team for their amazing work
- The .NET community for their continuous support
Contact Email: shadykhalifa.dotnetdev@gmail.com
Project Link: https://github.com/shady78/MultiSchema.DbContext.Dynamic
⭐️ If this project helped you, please consider giving it a star on GitHub!