sql server -如何用c#从已有的数据库中创建新的数据库

本文关键字:数据库 创建 server 何用 sql | 更新日期: 2023-09-27 17:53:24

我想用c#创建一个新的数据库。我只想从用户界面传递数据库名称,对于该数据库名称,我想运行数据库的sql脚本,为新数据库创建该脚本的相同模式。

sql server -如何用c#从已有的数据库中创建新的数据库

我不知道您打算怎么做,但是我已经完成了一些功能,将一些默认数据种子到主表。

//sql文件位置

private static readonly string IndexScriptSeedMasterDataLocation = "SqlSeedMasterData.sql";

在函数中我有:

 private static void SeedMasterData ( IpDataContext context, string databaseName)
{
  context.Database.CreateIfNotExists();
  var sqlContent = Content(IndexScriptSeedMasterDataLocation);
  var modifiedSqlScript = sqlContent.Replace("@DatabaseName", databaseName);
  context.Database.ExecuteSqlCommand(modifiedSqlScript);
}

//内容函数

private static string Content(string fileLocation)
{
 using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileLocation))
    {
      if (stream == null)
       {
          return string.Empty;
       }
       var streamReader = new StreamReader(stream);
       return streamReader.ReadToEnd();
     }
}