.net core webapi+EF Core
一.描述:
EF Core必须下载.net core2.0版本
Micorsoft.EntityFrameworkCore:EF框架的核心包
Micorsoft.EntityFrameworkCore.SqlServer:针对SqlServer数据库的扩展,使用SqlServer数据库必须。类似的还有MySql,SqlLite等
Micorsoft.EntityFrameworkCore.Tools
Micorosft.EntityFrameworkCore.Design:用户根据现有的数据库生成模型代码
Microsoft.EntityFrameworkCore.SqlServer.Design
二.EF安装:
通过nuget方式:
1.EF核心库安装:
Install-package Microsoft.EntityFrameworkCore
Install-package Microsoft.EntityFrameworkCore.SqlServer
2.dbfirst需要的库:
Install-package Microsoft.EntityFrameworkCore.Design Install-package Microsoft.EntityFrameworkCore.Tools Install-package Microsoft.EntityFrameworkCore.SqlServer.Design
三.使用dbfirst方式生成实体及上下文对象:
Scaffold-DbContext "Server=.;database=CommonPermission;User ID=sa;Password=123;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
四.配置:
通过上面的生成方式数据库配置直接在代码中,这种做法是不好的,应该移动到配置文件中:
上下文类屏蔽数据库连接:
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. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. //optionsBuilder.UseSqlServer("Server=.;database=CommonPermission;User ID=sa;Password=123;"); } }
在appsettings.json文件中配置:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "ConnectionStrings": { "SQLConnection": "Server=.;database=CommonPermission;User ID=sa;Password=123;" }, "AllowedHosts": "*" }
在Startup.cs文件中的ConfigureServices方法中注入上下文对象:
//注入上下文对象 services.AddDbContext<CommonPermissionContext>(x => x.UseSqlServer(Configuration.GetConnectionString("SQLConnection")));
接下来的和net framework中的ef方式一致!