zoukankan      html  css  js  c++  java
  • 在ASP.NET Core 2.0 web项目中使用EntityFrameworkCore

    一、安装EFCode包

      EFCore需要根据不同的数据库选择不同的数据库提供程序database provider,各数据库的包地址:https://docs.microsoft.com/zh-cn/ef/core/providers/

    使用sqlserver数据库使用的是Microsoft.EntityFrameworkCore.SqlServer包,支持SQL Server 2008 及以上版本

    Microsoft.EntityFrameworkCore.SqlServer包依赖Microsoft.EntityFrameworkCore 和Microsoft.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;
            }
    }

      

  • 相关阅读:
    HDU 2544 (Djikstra)
    HDU 1237(表达式求值)
    HDU1690 (Floyd)
    《大道至简》读后感
    第6周总结
    第8周总结
    第7周总结
    第四周总结
    第5周总结
    java程序
  • 原文地址:https://www.cnblogs.com/tangchun/p/8758851.html
Copyright © 2011-2022 走看看