在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM