博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
.NetCore中EFCore的使用整理
阅读量:6995 次
发布时间:2019-06-27

本文共 4089 字,大约阅读时间需要 13 分钟。

EntirtyFramework框架是一个轻量级的可扩展版本的流行实体框架数据访问技术.

其中的.NetCore版本对应EntityFrameworkCore

Git源代码地址:

官方使用文档说明:

一、安装Nuget包

Install-package Microsoft.EntityFrameworkCoreInstall-package Microsoft.EntityFrameworkCore.SqlServer
Micorsoft.EntityFrameworkCore:EF框架的核心包 Micorsoft.EntityFrameworkCore.SqlServer:针对SqlServer数据库的扩展,使用SqlServer数据库必须。类似的还有MySql,SqlLite等 Micorsoft.EntityFrameworkCore.Tools &Micorosft.EntityFrameworkCore.Design:用户根据现有的数据库生成模型代码等 ,更多参考 :二、使用实例 1.安装Nuget包之后,手动创建上下文,并 注入sql链接字符串
using Microsoft.EntityFrameworkCore;namespace Core2{    public class TestContext : DbContext    {        //public TestContext(DbContextOptions
options) : base(options) //{ //} protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //注入Sql链接字符串 optionsBuilder.UseSqlServer(@"Server=.;Database=Test1;Trusted_Connection=True;"); } public DbSet
Numeber1s { get; set; } }}
View Code
2.手写实体类,只要数据库中 存在对应 的表就可以了
using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;namespace Core2{    [Table("Numeber1")]    public class Numeber1    {        [Key]        public int ID { get; set; }        public decimal Num1 { get; set; }    }}
View Code

3.测试代码:

static void TestOne(){    TestContext _context = new TestContext();    int count = _context.Numeber1s.Count();    Console.WriteLine(count);}static void TestTwo(){    DateTime start = DateTime.Now;    TestContext _context = new TestContext();    for (int i = 0; i < 10000; i++)    {        _context.Numeber1s.Add(new Numeber1()        {            Num1 = i        });        _context.SaveChanges();    }    Console.WriteLine(_context.Numeber1s.Count());    Console.WriteLine("总时间,秒数:" + (DateTime.Now - start).TotalSeconds);}
View Code

在调试的状态下1万条插入数据执行时间:

三、根据数据库生成模型 1.安装EntityFrameworkCore.Design,EntityFrameworkCore.Tools,EntityFrameworkCore.SqlServer.Design 注:在EFCore2.0中只需要安装
EntityFrameworkCore.Tools
如果不需要自动根据数据库生成代码,这个几个类库可以不安装 。
Install-package Microsoft.EntityFrameworkCore.Design Install-package Microsoft.EntityFrameworkCore.Tools Install-package Microsoft.EntityFrameworkCore.SqlServer.Design
2.选择对应的项目,执行生成命名
Scaffold-DbContext "Server=.;database=test1;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models2

3.生成结果如下 : 四、Asp.Net Core中注册EF的上下文处理,在Startup文件中 1.注册服务
//配置EF的服务注册services.AddEntityFramework()    .AddDbContext
(options => { options.UseSqlServer(Configuration.GetConnectionString("SqlServer"), //读取配置文件中的链接字符串 b => b.UseRowNumberForPaging()); //配置分页 使用旧方式 });
2.修改上下文,重点指定DbContextOptions有外部配置
public NotifyBirdContext(DbContextOptions
opt) : base(opt) { }
3.在控制器中使用数据库上下文服务
NotifyBirdContext _Context = null;public ProjectController(NotifyBirdContext context){    _Context = context;}/// /// 获取可用项目数量/// /// 
[HttpGet("getcount")]public int GetCount(){ try { return _Context.Project.Count(); } catch (Exception ex) { throw ex; }}
五 、.Net Core中 EF  Core上下文配置 2,使用全局变量方式定义链接字符串 1.使用空参数构造器的上下文
/// /// 全局定义数据连接字符串/// public static string ConStr { get; set; }protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){    //optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;database=NotifyBird;Trusted_Connection=True;");    //配置数据链接    optionsBuilder.UseSqlServer(ConStr,b=>b.UseRowNumberForPaging());}

2.程序 启动注册链接

public void ConfigureServices(IServiceCollection services){    // Add framework services.    services.AddMvc();    NotifyBirdContext.ConStr = Configuration.GetConnectionString("SqlServer");}

3.任意位置实例化,上下文使用

///         /// 获取可用项目数量        ///         /// 
[HttpGet("getcount")] public int GetCount() { try { NotifyBirdContext _Context = new NotifyBirdContext(); return _Context.Project.Count(); } catch (Exception ex) { throw ex; } }
更多 :

转载地址:http://azsvl.baihongyu.com/

你可能感兴趣的文章