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

.NET MAUI依赖注入使用AddDbContext报错的解决方案咨询

解决.NET MAUI中AddDbContext的CS1061错误

1. 安装必要的NuGet包

AddDbContext是Entity Framework Core的扩展方法,必须先安装对应包:

  • 核心包:Microsoft.EntityFrameworkCore
  • 数据库提供程序包(根据你使用的数据库选择):比如SQLite用Microsoft.EntityFrameworkCore.Sqlite,SQL Server用Microsoft.EntityFrameworkCore.SqlServer

2. 添加using指令

在你的扩展方法所在文件顶部添加:

using Microsoft.EntityFrameworkCore;

3. 修正代码中的错误

你的代码存在两处问题:参数名拼写错误,且未指定数据库提供程序,修正后的代码示例:

public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
{
    var connectionString = configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<StoreCustomersContext>(opt =>
    {
        opt.UseSqlite(connectionString); // 替换为你的数据库提供方法,如UseSqlServer
    });
    return services; // 确保返回IServiceCollection以支持链式调用
}

4. 在MAUI项目中注册服务

在MauiProgram.cs的CreateMauiApp方法中调用该扩展方法:

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiApp<App>()
    .ConfigureFonts(fonts =>
    {
        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
    });

builder.Services.AddInfrastructureServices(builder.Configuration);

return builder.Build();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:42:35