一、安装EFCode包
EFCore需要根据不同的数据库选择不同的数据库提供程序database provider,各数据库的包地址:
使用sqlserver数据库使用的是包,支持SQL Server 2008 及以上版本
包依赖Microsoft.EntityFrameworkCore
和Microsoft.EntityFrameworkCore.Relational两个包
新建Core2 Web Application (Model-View-Controller)项目, 已经默认安装到了 元包里面,不需要再次安装
二、建立实体并添加EF上下文
给每个实体创建一个DbSet属性,每一个Dbset相当于数据库的一张表,每一个实体相当于数据库的一行
public class EFDbContext : DbContext { public EFDbContext(DbContextOptionsoptions) : base(options) { } public DbSet Admins { get; set; } public DbSet Companies { get; set; }}
可以重写DbContext的OnModelCreating来指定实体对应的数据库表名,默认数据库使用实体的复数做为表名
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().ToTable("Admin"); }
三、在DI注册EF上下文,Startup.cs文件里面的ConfigureServices方法里面注册EF上下文
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().AddJsonOptions(option => { option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); } ); }
数据库连接配置在appsettings.json文件里面:
"ConnectionStrings": { "DefaultConnection": "Data Source=.\\SQLExpress;Initial Catalog=DbTest;User ID=sa;Password=sa" },
DI会在创建控制器时,通过构造函数注入EF上下文,
public class AdminsController : SysBaseController { private readonly EFDbContext _context; public AdminsController(EFDbContext context) { _context = context; }}