【EF Core】上下文(DBContext)

DBContext实例化的4种方式

(1). ConfigureService中注入,然后在控制器注入上下文即可。

services.AddDbContext<YpfDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("EFStr")));

(2). 直接new上下文,可以将连接字符在构造函数中传递进去。

public class ApplicationDbContext : DbContext
{
    private readonly string _connectionString;

    public ApplicationDbContext(string connectionString)
    {
        _connectionString = connectionString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_connectionString);
    }
}
//调用
using var context = new ApplicationDbContext("Server=xxxxx;Database=CoreFrameDB;User ID=CoreFrameDB;Password=123456;");

(3). 创建 DbContextOptions,并可以显式调用构造函数:

var contextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
    .UseSqlServer(@"Server=xxxxx;Database=CoreFrameDB;User ID=CoreFrameDB;Password=123456;")
    .Options;

using var context = new ApplicationDbContext(contextOptions);

(4). 使用 AddDbContextFactory 工厂创建

posted @ 2022-04-23 08:24  .Neterr  阅读(335)  评论(0编辑  收藏  举报