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

ASP.NET Core中DbContext SQL连接异常,请求问题排查指引

问题排查:ASP.NET Core EF Core连接SQL Server依赖注入错误

我是ASP.NET Core新手,使用Entity Framework Core连接本地SQL Server数据库。当前项目采用.NET 7运行时与Web App Core模板,而非.NET 6与MVC模板。


项目结构与代码

Program.cs

using CommentsApplication.Db;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<DBconnection>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("localhost"));
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

Dbconnection.cs(DbContext类)

数据库中有一张accounts表,对应的DbContext代码:

using CommentsApplication.Models;
using Microsoft.EntityFrameworkCore;

namespace CommentsApplication.Db
{
    public class DBconnection: DbContext
    {
        public DBconnection(DbContextOptions<DBconnection> options) : base(options) { }

        public DbSet<Account> accounts { get; set; }
    }
}

Account实体类

using System.ComponentModel.DataAnnotations;

namespace CommentsApplication.Models
{
    public class Account
    {
        [Key]
        public int Id { get; set; }
        public string Organization { get; set; }
        public string Email { get; set; }
    }
}

连接字符串

Server=ZURG;Database=AccountsDB;Trusted_Connection=True;Encrypt=False;

错误信息

InvalidOperationException: Unable to resolve service for type 'System.Data.Common.DbConnection' while attempting to activate 'CommentsApplication.Pages.IndexModel'.


IndexModel代码

using CommentsApplication.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.Common;

namespace CommentsApplication.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        private readonly DbConnection _db;

        public string org { get; set; }
        public string email { get; set; }

        public IndexModel(ILogger<IndexModel> logger, DbConnection DB)
        {
            _logger = logger;
            _db = DB;
        }

        public void OnGet()
        {
        }

        public void OnPost(string org, string email)
        {
            org = org.Trim();
            email = email.Trim();

            Account a = new Account()
                            { 
                                Organization= org, 
                                Email = email 
                            };
        }
    }
}

排查方向与解决方案

  • 核心问题:你在IndexModel中注入了DbConnection,但依赖注入容器中并未注册这个通用类型。你已经正确注册了自定义的DBconnection(DbContext),应该注入这个类型而非DbConnection。
  • 修改步骤:
    1. 在IndexModel中添加CommentsApplication.Db命名空间引用
    2. 将构造函数中的DbConnection参数替换为DBconnection,同步修改私有字段类型
    3. 如果需要保存数据,在OnPost方法中通过DBconnection操作数据库
  • 修改后的IndexModel示例:
using CommentsApplication.Db;
using CommentsApplication.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace CommentsApplication.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly DBconnection _db;

        public string org { get; set; }
        public string email { get; set; }

        public IndexModel(ILogger<IndexModel> logger, DBconnection db)
        {
            _logger = logger;
            _db = db;
        }

        public void OnGet()
        {
        }

        public void OnPost(string org, string email)
        {
            org = org.Trim();
            email = email.Trim();

            Account a = new Account()
                            { 
                                Organization= org, 
                                Email = email 
                            };
            
            // 新增:通过DbContext将数据写入数据库
            _db.accounts.Add(a);
            _db.SaveChanges();
        }
    }
}
  • 额外检查:确认appsettings.json中ConnectionStrings节点下的键名与Program.cs中GetConnectionString("localhost")的参数完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:30:30