You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将旧MVC版本DBContext及数据查询代码迁移至.NET 6的方法

.NET 6下迁移GetUsername方法并解决APContext为空问题

核心原因说明

你之前手动实例化APContext为空,是因为修改后的APContext仅保留了带DbContextOptions<APContext>参数的构造函数,手动new时没有传入正确的配置选项,导致上下文无法初始化数据库连接。.NET 6中DbContext需通过**依赖注入(DI)**管理,由框架自动注入配置好的选项。

步骤1:创建独立的业务类(迁移GetUsername方法)

新建一个类文件(比如UserService.cs),将GetUsername方法迁移到这里,并通过构造函数注入APContext:

public class UserService
{
    private readonly APContext _dbContext;

    // 依赖注入获取已配置好的APContext实例
    public UserService(APContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<string> GetUsername(int userId)
    {
        return await _dbContext.Users
            .Where(w => w.Id == userId)
            .Select(x => x.Username)
            .FirstOrDefaultAsync();
    }
}

步骤2:注册服务到DI容器

在Program.cs中,将新建的UserService添加到服务集合,确保框架可以注入它:

// 原有的APContext注册代码之后添加
builder.Services.AddSqlServer<APContext>(builder.Configuration.GetConnectionString("DefaultConnection"));
// 注册UserService,使用Scoped生命周期(和DbContext默认生命周期一致)
builder.Services.AddScoped<UserService>();

步骤3:使用示例(在Controller中调用)

在需要调用该方法的地方(比如Controller),通过构造函数注入UserService并使用:

[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
    private readonly UserService _userService;

    public UserController(UserService userService)
    {
        _userService = userService;
    }

    [HttpGet("get-username/{userId}")]
    public async Task<IActionResult> GetUsername(int userId)
    {
        var username = await _userService.GetUsername(userId);
        return Ok(username);
    }
}

额外优化(可选)

如果需要保持原有的惰性加载和代理创建禁用设置,可以在APContext的构造函数中添加:

public APContext(DbContextOptions<APContext> options) : base(options)
{
    ChangeTracker.LazyLoadingEnabled = false;
    ChangeTracker.ProxyCreationEnabled = false;
}

内容的提问来源于stack exchange,提问作者Howard Hee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:43:27