gpt4 book ai didi

c# - 如何以编程方式发布 SQL Server 数据库项目?

转载 作者:太空狗 更新时间:2023-10-30 00:42:45 26 4
gpt4 key购买 nike

考虑以下情况:

现在,我有一个 C# 应用程序,它解析文件以获取详细信息(表、列等)并启动新的 SQL 连接以执行 SQL 命令以在数据库中创建这些表。

我想要的是创建一个 SQL 项目,我将在其中手动创建这些表,然后我想从 C# 应用程序以编程方式将 SQL 项目发布到某个服务器和数据库。

这可能吗?

最佳答案

如果您在 .NET 4 及更高版本中使用基于 sqlproj 的项目,您可以使用 Microsoft.Build 命名空间中的类以编程方式相当轻松地构建和发布它。摘 self 的回答here :

using Microsoft.Build.Framework;
using Microsoft.Build.Execution;

public void UpdateSchema() {
var props = new Dictionary<string, string> {
{ "UpdateDatabase", "True" },
{ "PublishScriptFileName", "schema-update.sql" },
{ "SqlPublishProfilePath", "path/to/publish.xml") }
};

var projPath = "path/to/database.sqlproj";

var result = BuildManager.DefaultBuildManager.Build(
new BuildParameters { Loggers = new[] { new ConsoleLogger() } },
new BuildRequestData(new ProjectInstance(projPath, props, null), new[] { "Publish" }));

if (result.OverallResult == BuildResultCode.Success) {
Console.WriteLine("Schema update succeeded!");
}
else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Schema update failed!");
Console.ResetColor();
}
}

private class ConsoleLogger : ILogger
{
public void Initialize(IEventSource eventSource) {
eventSource.ErrorRaised += (sender, e) => {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ResetColor();
};
eventSource.MessageRaised += (sender, e) => {
if (e.Importance != MessageImportance.Low)
Console.WriteLine(e.Message);
};
}
public void Shutdown() { }
public LoggerVerbosity Verbosity { get; set; }
public string Parameters { get; set; }
}

这适用于 .NET 4 及更高版本。确保并包含对 Microsoft.BuildMicrosoft.Build.Framework 的程序集引用。

关于c# - 如何以编程方式发布 SQL Server 数据库项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13843990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com