在 .NET Core Web API 项目中使用 OnConfiguring() 或 Services.AddDbContext() 在 DbContext 中配置连接有什么区别?

问题描述 投票:0回答:0

我正在使用 .NET Core 和 Entity Framework 构建 REST API,我不确定以下两种方法的区别。

选项一

在实现

DbContext
的类中,我可以像这样在
OnConfiguring()
方法中配置连接:

public class GameContext : DbContext
{
    public GameContext(DbContextOptions<GameContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlServer("DbConnectionString");
    }

    public DbSet<Game> Games { get; set; }
}

选项2

或者,我可以使用

Program.cs
Services.AddDbContext()
中配置连接,如下所示:

builder.Services.AddDbContext<GameContext>(options => options.UseSqlServer("DbConnectionString"));

有人可以解释这两种方法之间的区别吗?喜欢:

  • 使用
    OnConfiguring()
    Services.AddDbContext()
    之间有什么性能差异吗?
  • 在什么情况下一种方法可能比另一种方法更合适?
c# asp.net-core entity-framework-core asp.net-core-webapi database-connection
© www.soinside.com 2019 - 2024. All rights reserved.