Asp.net core 使用EntityFrame Work

安装以下Nuget 包

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Design

Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore

Microsoft.EntityFrameworkCore.SqlServer或者Npgsql.EntityFrameworkCore.PostgreSQL

安装完上述Nuget包之后,在appsettings配置文件中配置连接字符串.如下:

XML 复制代码
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "anna": "Host=10.10.11.185;Port=5432;Database=Films;Username=postgres;Password=money13;"
  }
}

之后,在程序包管理控制台,执行下述命令,即可生成DbContext/ Model,注意,同步修改连接字符串/生成目录等.

bash 复制代码
Scaffold-DbContext 'Name=ConnectionStrings:anna' Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models -ContextDir Context -Context FilmContext

如果修改了数据库,需要再次生成,执行如下命令:

bash 复制代码
Scaffold-DbContext 'Name=ConnectionStrings:anna' Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models -ContextDir Context -Context FilmContext -Force

上述代码,只能在Asp.net Core项目中运行。如果EF放到类库中,无Asp.Net Core环境,运行上述脚本,报错

A named connection string was used, but the name 'ConnectionStrings:anna' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

提示未找到连接字符串,经过检索,问DeepSeek,发现是脱离Asp.Net Core环境执行上述脚本,会导致无法获取连接字符串。

解决方案是,直接在脚本中写明连接字符串。如下:

bash 复制代码
Scaffold-DbContext "Host=192.168.11.185;Database=money2DB;Username=postgres;Password=mm123;" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models -ContextDir Context -Context OM2Context

执行完上述操作后,即配置完EF环境.

在Program.cs中,添加下述代码,配置EF

cs 复制代码
builder.Services.AddEntityFrameworkNpgsql();
builder.Services.AddDbContext<FilmContext>(options =>
    options.UseNpgsql(builder.Configuration.GetConnectionString("anna")));

之后,在控制器中通过注入的方式,使用DbContext ,注意,如果通过new的方式实例化,会报错.

cs 复制代码
private readonly FilmContext _context;

public SecondController(ILogger<SecondController> logger, FilmContext context)
{
    this.logger = logger;
    logger.LogInformation($"{this.GetType()} 被构造了");
    _context = context;
}
相关推荐
XMYX-02 小时前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
@yanyu6664 小时前
springboot实现查询学生
java·spring boot·后端
酷爱码4 小时前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
AI小智5 小时前
Google刀刃向内,开源“深度研究Agent”:Gemini 2.5 + LangGraph 打造搜索终结者!
后端
java干货5 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
一只叫煤球的猫5 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql
写bug写bug6 小时前
如何正确地对接口进行防御式编程
java·后端·代码规范
豌豆花下猫7 小时前
Python 潮流周刊#105:Dify突破10万星、2025全栈开发的最佳实践
后端·python·ai