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

我的Database Context引用始终返回null,该如何修复?

问题原因

你实例化MorningOrders类时调用了无参构造函数,该构造函数没有对_context字段做任何赋值操作,因此调用CompleteOrders方法访问_context时就会触发空引用错误。

修复方案

方案1:使用ASP.NET Core依赖注入(推荐)

这是.NET Core/.NET 5+项目的标准实现方式,步骤如下:

  1. 在Startup.cs的ConfigureServices方法中注册服务:
public void ConfigureServices(IServiceCollection services)
{
    // 先确保你的数据库上下文已注册,替换为你实际的数据库配置
    services.AddDbContext<EbContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("你的数据库连接字符串名称")));

    // 注册MorningOrders到依赖注入容器
    services.AddScoped<MorningOrders>();

    // 其他原有服务注册逻辑...
}
  1. 不要手动new实例,通过依赖注入获取MorningOrders实例:
    如果你需要在Startup.cs的Configure方法中执行调用,直接从方法参数注入即可:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, MorningOrders meds)
{
    // 直接调用方法,无需手动实例化
    meds.CompleteOrders();

    // 其他原有配置逻辑...
}

如果需要手动解析服务,使用以下方式:

using var serviceScope = app.ApplicationServices.CreateScope();
var meds = serviceScope.ServiceProvider.GetRequiredService<MorningOrders>();
meds.CompleteOrders();

方案2:手动传入上下文(不推荐)

如果确实需要手动实例化,调用带参数的构造函数并传入初始化好的EbContext实例:

// 手动构造数据库上下文配置
var dbOptions = new DbContextOptionsBuilder<EbContext>()
    .UseSqlServer("你的实际数据库连接字符串")
    .Options;
var context = new EbContext(dbOptions);

// 调用带参数的构造函数
MorningOrders meds = new MorningOrders(context);
meds.CompleteOrders();

优化建议

删除MorningOrders类的无参构造函数,添加入参空校验,避免后续误调用导致空引用问题:

public class MorningOrders
{
    private readonly EbContext _context;

    // 删除无参构造函数,强制必须传入上下文
    public MorningOrders(EbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public bool CompleteOrders()
    { 
        // 原有订单处理逻辑
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:30:01