• .NetCore中EFCore的使用整理


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

    其中的.NetCore版本对应EntityFrameworkCore

    Git源代码地址:https://github.com/aspnet/EntityFramework/

    官方使用文档说明:https://docs.microsoft.com/zh-cn/ef/core/index

    一、安装Nuget包

    Install-package Microsoft.EntityFrameworkCore
    Install-package Microsoft.EntityFrameworkCore.SqlServer
    Micorsoft.EntityFrameworkCore:EF框架的核心包
    Micorsoft.EntityFrameworkCore.SqlServer:针对SqlServer数据库的扩展,使用SqlServer数据库必须。类似的还有MySql,SqlLite等
    Micorsoft.EntityFrameworkCore.Tools
    &Micorosft.EntityFrameworkCore.Design:用户根据现有的数据库生成模型代码等 ,更多参考 :https://docs.microsoft.com/zh-cn/ef/efcore-and-ef6/porting/port-edmx
    二、使用实例
    1.安装Nuget包之后,手动创建上下文,并 注入sql链接字符串
    using Microsoft.EntityFrameworkCore;
    namespace Core2
    {
        public class TestContext : DbContext
        {
            //public TestContext(DbContextOptions<TestContext> options) : base(options)
            //{
    
            //}
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                //注入Sql链接字符串
                optionsBuilder.UseSqlServer(@"Server=.;Database=Test1;Trusted_Connection=True;");
            }
            public DbSet<Numeber1> 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<NotifyBirdContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("SqlServer"), //读取配置文件中的链接字符串
                b => b.UseRowNumberForPaging());  //配置分页 使用旧方式
        });

    2.修改上下文,重点指定DbContextOptions有外部配置
            public NotifyBirdContext(DbContextOptions<NotifyBirdContext> opt) : base(opt)
            {
    
            }
    3.在控制器中使用数据库上下文服务
    NotifyBirdContext _Context = null;
    public ProjectController(NotifyBirdContext context)
    {
        _Context = context;
    }
    /// <summary>
    /// 获取可用项目数量
    /// </summary>
    /// <returns></returns>
    [HttpGet("getcount")]
    public int GetCount()
    {
        try
        {
            return _Context.Project.Count();
        }
        catch (Exception ex)
        {
    
            throw ex;
        }
    }
    五 、.Net Core中 EF  Core上下文配置 2,使用全局变量方式定义链接字符串
    1.使用空参数构造器的上下文
    /// <summary>
    /// 全局定义数据连接字符串
    /// </summary>
    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.任意位置实例化,上下文使用

            /// <summary>
            /// 获取可用项目数量
            /// </summary>
            /// <returns></returns>
            [HttpGet("getcount")]
            public int GetCount()
            {
                try
                {
                    NotifyBirdContext _Context = new NotifyBirdContext();
                   return _Context.Project.Count();
                }
                catch (Exception ex)
                {
    
                    throw ex;
                }
            }
    更多 :
    VS Code搭建.NetCore开发环境(二)
    VS Code搭建.NetCore开发环境(一)
    Chocolatey 简介(软件自动化管理工具)
  • 相关阅读:
    2021-5-14 日报博客
    2021-5-13 日报博客
    2021-5-11 日报博客
    2021-5-10 日报博客
    2021-5-8 周报博客
    团队介绍——北部大队
    周总结4
    梦断代码阅读笔记02
    周总结3
    周总结2
  • 原文地址:https://www.cnblogs.com/tianma3798/p/6835400.html
Copyright © 2020-2023  润新知