Using Microsoft.Build.Evaluation to publish a database project (.sqlproj)

后端 未结 4 2018
耶瑟儿~
耶瑟儿~ 2020-12-09 04:57

I need to be able to publish an SSDT project programmatically. I am looking at using Microsoft.Build to do so but can not find any documentation. It seems pretty simple to c

4条回答
  •  -上瘾入骨i
    2020-12-09 05:30

    I wanted to build and publish a database based on a sqlproj file and log helpful information to console. Here's what I arrived at:

    using Microsoft.Build.Framework;
    using Microsoft.Build.Execution;
    
    public void UpdateSchema() {
        var props = new Dictionary {
            { "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; }
    }
    

    This is for .NET 4 and above. Be sure and include assembly references to Microsoft.Build and Microsoft.Build.Framework.

提交回复
热议问题