微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐