什么是EFCore CLI

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

image

获取EFCore CLI

安装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

参考

原文地址:http://www.cnblogs.com/taylorshi/p/16843914.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性