.NET Core Method for Obtaining Database Context Instance and Configuring Connection Strings
[TOC]
Assuming the database has two tables: User and Blogs,
The model classes are as follows:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public string Email { get; set; }
}
public class Blogs
{
public int Id { get; set; }
public string BlogName { get; set; }
public string Url { get; set; }
}
The database context roughly looks like this:
public class DataContext : DbContext
{
public DataContext()
{
}
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Blogs> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
/*
* Other implementations
*/
}
Dependency Injection in ASP.NET Core
The database injection in ASP.NET Core is straightforward and convenient, configured in ConfigureServices
.
services.AddDbContext<DataContext>(options => options.UseSqlite("filename=Database.db"));
Then, it can be used directly in controllers without any extra code.
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly DataContext _context;
public WeatherForecastController(DataContext context)
{
_context = context;
}
}
Dependency Injection in .NET Core
You need to install a NuGet package:
Microsoft.Extensions.DependencyInjection
Create a class ContextService
for configuring injection and obtaining the context.
public class ContextService
{
/// <summary>
/// Configure various services
/// </summary>
/// <returns></returns>
public static IServiceProvider ServiceProvider()
{
IServiceCollection services = new ServiceCollection();
services.AddDbContext<DataContext>(options => options.UseSqlite("filename=Database.db"));
var serviceProvider = services.BuildServiceProvider();
return serviceProvider;
}
/// <summary>
/// Get context
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static DataContext GetContext(IServiceProvider services)
{
var sqliteContext = services.GetService<DataContext>();
return sqliteContext;
}
/// <summary>
/// Get context
/// </summary>
public static DataContext GetContext()
{
var services = ServiceProvider();
var sqliteContext = services.GetService<DataContext>();
return sqliteContext;
}
}
When needed, the context can be obtained like this:
var context = ContextService.GetContext();
var list = context.Users.ToList();
Unsign Context Configuration in OnConfiguring
In the above two examples, the connection string is configured using Action<DbContextOptionsBuilder> optionsAction
.
options => options.UseSqlite("filename=Database.db")
We can directly configure the default connection string in the context's OnConfiguring
method.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
#if DEBUG
optionsBuilder.UseSqlite("filename=Database.db");
#endif
}
However, this is strongly discouraged; typically, it may only be done in a debugging environment or for convenience.
This situation occurs when the context has a parameterless constructor, allowing external code to directly instantiate the context.
var context = new DataContext();
var list = context.Users.ToList();
In this case, the context is directly instantiated, using the default connection string.
OnConfiguring
will only take effect when there is no injection or when a parameterless constructor is used, or in other words, it has the lowest priority among various context configuration methods.
Context Constructor with Parameters and Self-instantiation
The context must have a constructor with DbContextOptions
or DbContextOptions<T>
, and it is recommended to use the generic form.
Constructor example:
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
With this constructor, configuration can be injected from outside, for example:
services.AddDbContext<DataContext>(options => options.UseSqlite("filename=Database.db"));
If you are not using injection (Microsoft.Extensions.DependencyInjection) or third-party IoC tools, then the above method cannot be used.
However, you can instantiate it yourself and pass the configuration object:
var optionsBuilder = new DbContextOptionsBuilder<DataContext>();
optionsBuilder.UseSqlite("filename=Database.db");
DataContext context = new DataContext(optionsBuilder.Options);
var list = context.Users.ToList();
DbContextOptions Constructor
DatabaseContext context = new DatabaseContext(options: new DbContextOptionsBuilder<DatabaseContext>().UseSqlite("H:/临时/database/Database.db").Options);
DbContextOptionsBuilder
is a constructor for DbContextOptions
, used to customize the construction of DbContextOptions
in various situations. In the above examples, this builder can be conveniently used to construct the context.
whuanle is relatively inexperienced... There are many principles above I don't quite understand. If any experts see this, please provide guidance!
文章评论