简体   繁体   中英

EF Core Database.EnsureCreated get creating table SQL and without sending request to database

I use EF Core - Database.EnsureCreated to create table by C# class, but now I'd like to get only creating table and columns SQL and without sending request to database.

eg

public class ApplicationDbContext : DbContext
{
    public DbSet<Dto> Dtos{ get; set; }
}

public class Dto
{
  [Key]
  [StringLength(10)]
    public string ID{ get; set; }
  [StringLength(100)]
  [Required]
    public string Name{ get; set; }
  [Required]
  public int Age{ get; set; }
}

db.Database.EnsureDeleted();

Expected result :

create table Dto
{
  ID nvarchar(10) primary key not null,
  Name nvarchar(100) not null,
  Age int not null
}

What I tried?

I did open SSMS profile and get SQL from EF Core, but it needs to send request to database.

My usual approach to these types of questions is to poke around in the source code . I found the implementation of .EnsureCreated() , then noticed that there is a public method to .GenerateCreateScript() on the same type. Searching the entire code base for calls to that method reveals an extension method on DatabaseFacade . So all you need to do is;

var sqlSource = db.Database.GenerateCreateScript();

However using google to search for that method doesn't reveal any results in the official documentation. The "proper" way to create a production database is to create migrations, then create an sql script to apply them.

You can use the dotnet EF CLI to run the migrations script:

dotnet ef migrations script -i -o "C:\MYFOLDER\dbscript.sql"

REF: https://docs.microsoft.com/en-us/ef/core/cli/dotnet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM