1. 程式人生 > >在ASP.NET Core 2.0 web項目中使用EntityFrameworkCore

在ASP.NET Core 2.0 web項目中使用EntityFrameworkCore

settings void builder readonly tar providers base ride data-

一、安裝EFCode包

  EFCore需要根據不同的數據庫選擇不同的數據庫提供程序database provider,各數據庫的包地址:https://docs.microsoft.com/zh-cn/ef/core/providers/

使用sqlserver數據庫使用的是Microsoft.EntityFrameworkCore.SqlServer包,支持SQL Server 2008 及以上版本

Microsoft.EntityFrameworkCore.SqlServer包依賴Microsoft.EntityFrameworkCoreMicrosoft.EntityFrameworkCore.Relational兩個包

  新建Core2 Web Application (Model-View-Controller)項目,Microsoft.EntityFrameworkCore.SqlServer 已經默認安裝到了 Microsoft.AspNetCore.All元包裏面,不需要再次安裝

二、建立實體並添加EF上下文

  給每個實體創建一個DbSet屬性,每一個Dbset相當於數據庫的一張表,每一個實體相當於數據庫的一行

 public class EFDbContext : DbContext
    {
        public EFDbContext(DbContextOptions<EFDbContext> options) : base
(options) { } public DbSet<Admin> Admins { get; set; } public DbSet<Company> Companies { get; set; } }

  可以重寫DbContext的OnModelCreating來指定實體對應的數據庫表名,默認數據庫使用實體的復數做為表名

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity
<Admins>().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<EFDbContext>(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;
        }
}

  

在ASP.NET Core 2.0 web項目中使用EntityFrameworkCore