在ASP.Net Core Web API中使用EF Core
本文介绍了如何在ASP.Net Core Web API中使用EntityFrameworkCore,具体环境为:VS2019 + ASP.Net Core 3.1,并以Database First的形式使用EF Core。
1、通过Nuget引入类库
Microsoft.EntityFrameworkCore
Pomelo.EntityFrameworkCore.MySql
2、添加MySQL连接字符串(appsettings.json)
1 2 3 | "ConnectionStrings" : { "DefaultConnection" : "server=localhost; userid=root; pwd=root; database=TestDb; charset=utf8mb4; pooling=false" } |
3、添加DbContext
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class AppDbContext : DbContext { public IConfiguration Configuration { get ; } public AppDbContext(DbContextOptions<AppDbContext> options, IConfiguration configuration) : base (options) { Configuration = configuration; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base .OnConfiguring(optionsBuilder); var connectionString = Configuration.GetConnectionString( "DefaultConnection" ); optionsBuilder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); } public DbSet<WeatherForecast> WeatherForecast { get ; set ; } } |
4、在Startup类注入EF Core
1 2 3 4 5 6 7 8 9 10 | public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //注入EF Core services.AddDbContext<AppDbContext>(); //注入数据仓库(实例化注入) services.AddTransient<IWeatherForecastRepository, WeatherForecastRepository>(); } |
5、实现数据仓库模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public interface IWeatherForecastRepository { IEnumerable<WeatherForecast> GetAllWeatherForecasts(); } public class WeatherForecastRepository : IWeatherForecastRepository { private readonly AppDbContext _context; public WeatherForecastRepository(AppDbContext context) { _context = context; } public IEnumerable<WeatherForecast> GetAllWeatherForecasts() { return _context.WeatherForecast; } } |
6、在Controller中使用模型仓库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | [ApiController] [Route( "api/[controller]" )] public class WeatherForecastController : ControllerBase { private readonly IWeatherForecastRepository _repository; public WeatherForecastController(IWeatherForecastRepository repository) { _repository = repository; } [HttpGet] public IEnumerable<WeatherForecast> Get() { return _repository.GetAllWeatherForecasts(); } } |
7、注意事项
(1) Database First模式要求数据库及相应的表存在,因此需要预先手动添加数据库及表。
(2) Pomelo.EntityFrameworkCore.MySql需要引入“最新预发行版 5.0.0-alpha.2”,否则引入“最新稳定版 3.2.4”会出现下面异常(在Asp.Net Core 2.1版本应该可用):
System.IO.FileNotFoundException:“Could not load file or assembly 'Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. 系统找不到指定的文件。”
(3) DbContext相关类中的DbSet要使用表名称,即
1 | public DbSet<WeatherForecast> WeatherForecast { get ; set ; } |
如果使用复数形式
1 | public DbSet<WeatherForecast> WeatherForecasts { get ; set ; } |
会出现下面异常(同样在Asp.Net Core 2.1版本应该可用):
MySqlException: Table 'testdb.weatherforecasts' doesn't exist
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器