[英]How to create a database from sql script using Entity Framework Core?
I am starting a project with EF Core, were the database already exists.如果数据库已经存在,我正在使用 EF Core 启动一个项目。 I have the database structure as an sql script, that I would like to run every time I initialize the context, in order to have a fresh database every time I would run the application.
我将数据库结构作为 sql 脚本,每次初始化上下文时我都想运行它,以便每次运行应用程序时都有一个新的数据库。 Here follows a snippet from the traditional EF, showing what I would like to achieve with EF Core .
下面是传统 EF 的一个片段,展示了我想用 EF Core实现的目标。
internal sealed class AnnotationContextDatabaseInitializer : DropCreateDatabaseAlways<AnnotationContext>
{
public override void InitializeDatabase(AnnotationContext context)
{
base.InitializeDatabase(context);
context.Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction, File.ReadAllText("dropAndCreateEntireDatabase.sql"));
}
}
After getting more experienced with EF, I can see that it does not make sense to use the context for things like creating a DB.在对 EF 有了更多经验之后,我可以看到将上下文用于创建数据库之类的事情是没有意义的。 This would be a chicken egg problem, were the context is not valid has it misses the underlying tables.
这将是一个鸡蛋问题,如果上下文无效,它会错过基础表。
This does be done with a traditional SqlCommand , running a script that contains the DB.这确实是通过传统的 SqlCommand 完成的,运行包含数据库的脚本。
´´´ '''
public void ExecuteNonQuery(string query, string connectionString)
{
string[] splitter = new string[] {"\r\nGO"};
string[] commandTexts = query.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.RetryOpen();
foreach (var commandText in commandTexts)
{
try
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
connection.Close();
throw;
}
}
connection.Close();
}
}
´´´ '''
This can be run lets say in a test initialize.这可以在测试初始化中运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.