首页 > 其他分享 >乘风破浪,遇见最佳跨平台跨终端框架.Net Core/.Net生态 - 适用于Entity Framework Core的命令行(CLI)工具集(Dotnet-EF)

乘风破浪,遇见最佳跨平台跨终端框架.Net Core/.Net生态 - 适用于Entity Framework Core的命令行(CLI)工具集(Dotnet-EF)

时间:2022-10-31 12:55:50浏览次数:97  
标签:Core -- ef 指定 跨平台 参数 dotnet Net public

什么是EFCore CLI

适用于Entity Framework Core的命令行接口(CLI)工具可执行设计时开发任务。例如,可以创建迁移、应用迁移,并为基于现有数据库的模型生成代码。

image

获取EFCore CLI

https://github.com/TaylorShi/HelloEfCoreCli

安装EFCore CLI

全局安装

dotnet tool install --global dotnet-ef

image

更新EFCore CLI

dotnet tool update --global dotnet-ef

image

卸载EFCore CLI

dotnet tool uninstall --global dotnet-ef

image

前置条件

通常使用EFCore CLI之前,我们需要确保项目已经安装了Microsoft.EntityFrameworkCore.Design,否则将会提示你

Your startup project 'xxxxxxxxxxx.EFSqliteConsole' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.

终端切换到项目根目录,使用命令行安装它

https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Design

dotnet add package Microsoft.EntityFrameworkCore.Design

如果是Net Core 3.1项目,最新的版本无法兼容,可以追加版本号参数--version 5.0.17

验证EFCore CLI

dotnet ef

image

管理迁移

建立示例项目(Sqlite)

依赖包

https://www.nuget.org/packages/Microsoft.EntityFrameworkCore.Sqlite

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

如果是Net Core 3.1项目,最新的版本无法兼容,可以追加版本号参数--version 5.0.17

建立示例领域

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new List<Post>();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

建立示例DbContext

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    public BloggingContext()
    {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        DbPath = System.IO.Path.Join(path, "blogging.db");
    }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}

添加初始化迁移

dotnet ef migrations add $name

例如:

dotnet ef migrations add InitCreate

image

这个动作会创建一些迁移用的.cs文件,默认存放在项目根目录的Migrations文件夹中。

image

可选项

  • 如果要修改这个目录路径,可以使用参数:--output-dir|-o指定。
  • 如果要指定生成类的命名空间,可以使用参数:--namespace|-n指定。

列出可用的迁移

dotnet ef migrations list

image

可选项

  • 如果要指定用于连接到数据库的连接字符串,可以使用参数:--connection指定,默认为AddDbContextOnConfiguring中指定的值。
  • 如果要指定不要连接到数据库,可以使用参数:--no-connect指定。

回退上次的迁移

删除上一次迁移,回退为上一次迁移所做的代码更改。

dotnet ef migrations remove

image

可选项

  • 如果要如果连接到数据库时出错,则继续仅回退到代码更改,可以使用参数:--force|-f指定。

从迁移生成SQL脚本

我们可以基于迁移得到SQL脚本

dotnet ef migrations script $fromIndex $name

这里$fromIndex默认值就是0

可选项

  • 如果要指定生成脚本的文件路径,可以使用参数:--output|-o指定。
  • 如果要生成可在任何迁移时用于数据库的脚本,可以使用参数:--idempotent|-i指定。
  • 不要生成SQL事务语句,可以使用参数:--no-transactions指定。

例如从InitCreate的首次迁移前到它自身包括的SQL脚本

dotnet ef migrations script 0 InitCreate

image

这时候我们给Blog领域模型增加一个Title字段

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public string Title { get; set; }

    public List<Post> Posts { get; } = new List<Post>();
}

并且我们创建一个新的迁移UpdateBlogTitle

dotnet ef migrations add UpdateBlogTitle

image

这个时候,按道理就应该有两个迁移了,那么从InitCreate之后迁移的所有SQL脚本,就能够生成第二次UpdateBlogTitle的SQL脚本了

dotnet ef migrations script InitCreate

image

确实结果是这样的。

创建可执行文件更新数据库

dotnet ef migrations bundle

需要 >=Entity Framework Core 6.0.0

可选项

  • 如果要指定要创建的可执行文件的路径,可以使用参数:--output|-o指定。
  • 如果要覆盖现有文件,可以使用参数:--force|-f指定
  • 如果要同时绑定.NET 运行时,因此不需要在计算机上安装它,可以使用参数:--self-contained指定
  • 如果要要绑定的目标运行时,可以使用参数:--target-runtime指定

管理上下文

获取DbContext信息

dotnet ef dbcontext info

image

列出可用DbContext

dotnet ef dbcontext list

image

生成DbContext优化模型

dotnet ef dbcontext optimize

需要 >=Entity Framework Core 6.0.0

根据数据库生成代码

dotnet ef dbcontext scaffold $Connection $Provider

其中

  • $Connection,用于连接到数据库的连接字符串。
  • $Provider,要使用的提供程序,通常,这是NuGet包的名称,例如Microsoft.EntityFrameworkCore.SqlServer

可选项

  • 如果要使用属性配置模型,可以使用参数:--data-annotations|-d指定。
  • 如果要指定生成的DbContext类的名称,可以使用参数:--context指定。
  • 如果要指定放置DbContext类文件的目录,可以使用参数:--context-dir指定。
  • 如果要指定生成的DbContext类的命名空间,可以使用参数:--context-namespace指定。
  • 如果要覆盖现有文件,可以使用参数:--force|-f指定。
  • 如果要指定放置实体类文件的目录,可以使用参数:--output-dir|-o指定。
  • 如果要指定所有生成的类的命名空间,可以使用参数:--namespace|-n指定。
  • 如果要指定生成实体类型的表的架构,可以使用参数:--schema指定。
  • 如果要指定为其生成实体类型的表,可以使用参数:--table|-t指定。
  • 如果要使用与数据库中显示的名称完全相同的表和列名,可以使用参数:--use-database-names指定。
  • 如果要禁止在生成的DbContext类中生成OnConfiguring方法,可以使用参数:--no-onconfiguring指定。
  • 请勿使用复数化程序,可以使用参数:--no-pluralize指定。

例如

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models
dotnet ef dbcontext scaffold "DataSource=C:\Users\TaylorShi\AppData\Local\blogging.db" Microsoft.EntityFrameworkCore.Sqlite -o Models

image

image

dotnet ef dbcontext scaffold "DataSource=C:\Users\TaylorShi\AppData\Local\blogging.db" Microsoft.EntityFrameworkCore.Sqlite -o Models -t Blogs -t Posts --context-dir Context -c BlogContext --context-namespace TeslaOrder.EFSqliteConsole

image

image

public partial class BlogContext : DbContext
{
    public BlogContext()
    {
    }

    public BlogContext(DbContextOptions<BlogContext> options)
        : base(options)
    {
    }

    public virtual DbSet<Blog> Blogs { get; set; }
    public virtual DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
            optionsBuilder.UseSqlite("DataSource=C:\\Users\\TaylorShi\\AppData\\Local\\blogging.db");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>(entity =>
        {
            entity.HasIndex(e => e.BlogId, "IX_Posts_BlogId");

            entity.HasOne(d => d.Blog)
                .WithMany(p => p.Posts)
                .HasForeignKey(d => d.BlogId);
        });

        OnModelCreatingPartial(modelBuilder);
    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}

从DbContext生成SQL脚本

dotnet ef dbcontext script

可选项

  • 如果要指定生成的SQL脚本文件,可以使用参数:--output|-o指定。
  • 如果要指定DbContext,可以使用参数:--context|-c指定。

image

管理数据库

根据迁移更新数据库

dotnet ef database update $name

其中$name可以指定迁移的迁移名称。

可选项

  • 如果要指定用于连接到数据库的连接字符串,可以使用参数:--connection指定,默认为AddDbContextOnConfiguring中指定的值。

例如,不带参数代表开始首次迁移之前并会还原所有迁移

dotnet ef database update

image

image

dotnet ef database update 20221031043138_UpdateBlogName

image

另外>=Entity Framework Core 5.0.0还支持将其他参数传递到Program.CreateHostBuilder

dotnet ef database update -- --environment Production

其中--之后所有内容都会被视为参数,它将转发给应用去处理。

删除数据库

dotnet ef database drop

可选项

  • 如果不需要确认,直接删除,可以使用参数:--force|-f指定。
  • 如果显示要删除的数据库,但不删除它,可以使用参数:--dry-run指定。

image

参考

标签:Core,--,ef,指定,跨平台,参数,dotnet,Net,public
From: https://www.cnblogs.com/taylorshi/p/16843914.html

相关文章

  • 【C#进阶】.NET Core 中的筛选器 Filter
    官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/filters?view=aspnetcore-5.0 通过使用ASP.NETCore中的筛选器,可在请求处理管道中的特定阶......
  • M1芯片下运行Kubernetes
    买了一个新Mac,是M1芯片。本来想打算安装一下Minikube用来练习一下。(Minikube是一个本地安装的K8S集群,可以低成本学习)理想的步骤是按部就班: 1.安装brew /bin/bash-c......
  • Kubernetes学习笔记
    Kuberneteskubernetes,简称K8s,是Google开源的一个容器编排引擎,它支持自动化部署、大规模可伸缩、应用容器化管理。在生产环境中部署一个应用程序时,通常要部署该应用的......
  • .NET性能系列文章二:Newtonsoft.Json vs. System.Text.Json
    微软终于追上了?图片来自GlennCarstens-PetersUnsplash欢迎来到.NET性能系列的另一章。这个系列的特点是对.NET世界中许多不同的主题进行研究、基准和比较。正如标题......
  • 云原生之旅 - 6)不能错过的一款 Kubernetes 应用编排管理神器 Kustomize
    前言相信经过前一篇文章的学习,大家已经对Helm有所了解,本篇文章介绍另一款工具 Kustomize,为什么Helm如此流行,还会出现Kustomize?而且Kustomize自kubectl1.14以来早已......
  • 某 .NET RabbitMQ SDK 有采集行为,你怎么看?
    一:背景1.讲故事前几天有位朋友在微信上找到我,说他的一个程序上了生产之后,被运维监控定位到这个程序会向一个网址为:http://m.365ey.net上不定期打数据,而且还是加密的格......
  • ASP.NET Core教程-Configuration(配置)- 配置文件
    更新记录转载请注明出处:2022年10月31日发布。2022年10月28日从笔记迁移到博客。ASP.NETCore应用配置说明当我们需要将程序发布到不同环境中时,需要让应用支持配......
  • iOS数据持久化 - CoreData
    前言1-CoreData是苹果公司封装的进行数据持久化的框架,首次在iOS3.0版本系统中出现,它允许按照实体-属性-值模型组织数据,并以XML、二进制文件或者SQLite数据文件的......
  • Kubernetes学习笔记(四十一):KodeKloud Mock Exam - 3
    Question1(10')QuestionCreateanewserviceaccountwiththenamepvviewer.GrantthisServiceaccountaccesstolistallPersistentVolumesintheclusterb......
  • Jenkins Kubernetes Plugin
    JenkinsKubernetesPlugintorundynamicagentsinaKubernetescluster.BasedontheScalingDockerwithKubernetesarticle,automatesthescalingofJenkinsag......