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

Time:10-26

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.

e.g

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related