.net core 版本:3.1 mysql版本:5.6.28-mysql
1.批量映射数据库表
安装包:
Install-Package MySql.Data.EntityFrameworkCore Install-Package Pomelo.EntityFrameworkCore.MySql Install-Package Microsoft.EntityFrameworkCore.Tools Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
打开nuget控制台,输入以下命令
Scaffold-DbContext -Connection “server=127.0.0.1;uid=root;pwd=123456;database=xxxx;” -Provider Pomelo.EntityFrameworkCore.MySql -OutputDir Model -ContextDir Db -Context DbContext -UseDatabaseNames -Force
详见:
https://blog.csdn.net/andy5520/article/details/106839384
2.创建基本的依赖注入方式
注释掉:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
optionsBuilder.UseMySql("server=127.0.0.1;uid=root;pwd=123456;database=xxxx", Microsoft.EntityFrameworkCore.ServerVersion.Parse("5.6.28-mysql"));
}
}
在Startup - ConfigureServices 中注入dbcontext,注意UseMySql ,不要写成UseMySQL
// 注入dbcontext
services.AddDbContext<BookContext>(options =>
{
options.UseMySql(Configuration.GetConnectionString("MySqlConnection"), Microsoft.EntityFrameworkCore.ServerVersion.Parse("5.6.28-mysql"));
});
appsetting中添加数据库连接字符串:
//数据库连接字符串
"ConnectionStrings": {
"MySqlConnection": "Server=127.0.0.1;database=xxxx;uid=root;pwd=123456;"
}
创建测试TestController
private readonly ILogger<TestController> _logger;
private readonly BookContext _db;
public TestController(ILogger<TestController> logger, BookContext bookContext)
{
_logger = logger;
_db = bookContext;
}
[HttpGet]
public IEnumerable<pzkworkorder> Get()
{
List<pzkworkorder> data = new List<pzkworkorder>();
data = _db.pzkworkorders.Where(p => p.WORKORDERNUMBER == "GD2021071700007").ToList();
return data;
}
|