zoukankan      html  css  js  c++  java
  • 在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

  • 相关阅读:
    阿里早期Android加固代码的实现分析
    如何利用C++的time头文件获取系统时间
    Python编写基于socket的非阻塞多人聊天室程序(单线程&多线程)
    Dalvik模式下在Android so库文件.init段、.init_array段构造函数上下断点
    手动绕过百度加固Debug.isDebuggerConnected反调试的方法
    request使用代理
    requests爬取豆瓣热门电视剧
    scrapy-继承默认的user-agent 中间件
    scrapy-下载器中间件 随机切换user_agent
    scrapy 直接在编辑器运行
  • 原文地址:https://www.cnblogs.com/xhubobo/p/14408321.html
Copyright © 2011-2022 走看看