[英]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.我使用 EF Core - Database.EnsureCreated
通过 C# 类创建表,但现在我只想创建表和列 SQL,而不向数据库发送请求。
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.我确实打开了 SSMS 配置文件并从 EF Core 获取 SQL,但它需要向数据库发送请求。
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.我找到了.EnsureCreated()
的实现,然后注意到在同一类型上有一个.GenerateCreateScript()
的公共方法。 Searching the entire code base for calls to that method reveals an extension method on DatabaseFacade
.在整个代码库中搜索对该方法的调用会揭示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.创建生产数据库的“正确”方法是创建迁移,然后创建一个 sql 脚本来应用它们。
You can use the dotnet EF CLI to run the migrations script:您可以使用 dotnet EF CLI 运行迁移脚本:
dotnet ef migrations script -i -o "C:\MYFOLDER\dbscript.sql"
REF: https://docs.microsoft.com/en-us/ef/core/cli/dotnet参考: https : //docs.microsoft.com/en-us/ef/core/cli/dotnet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.