在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)
"ConnectionStrings": { "DefaultConnection": "server=localhost; userid=root; pwd=root; database=TestDb; charset=utf8mb4; pooling=false" }
3、添加DbContext
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
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //注入EF Core services.AddDbContext<AppDbContext>(); //注入数据仓库(实例化注入) services.AddTransient<IWeatherForecastRepository, WeatherForecastRepository>(); }
5、实现数据仓库模式
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中使用模型仓库
[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要使用表名称,即
public DbSet<WeatherForecast> WeatherForecast { get; set; }
如果使用复数形式
public DbSet<WeatherForecast> WeatherForecasts { get; set; }
会出现下面异常(同样在Asp.Net Core 2.1版本应该可用):
MySqlException: Table 'testdb.weatherforecasts' doesn't exist