在 C# 程序中存储查询的正确方法是什么?

What is the right way to store queries in a C# program?

我编写了一个程序,该程序使用 Azure API 到 运行 对 Azure 日志分析存储库的查询。

用于编写此查询的语言称为 Kusto。

我在 C# 代码中直接使用了很多 Kusto 查询。

像这样:

Client.ExecuteQuery(@"Heartbeat 
| summarize LastCall = max(TimeGenerated) by Computer 
| where LastCall < ago(15m)
| take 20");

有些查询很长,使代码非常难看。

是否有更好和更合适的方法来存储这些查询,例如在数据库中,这将有助于从代码中删除它们。

您可以将查询与您的源代码一起保存为文本文件,然后将它们与您的应用程序打包为 "Embedded Resources"。

此 post 中接受的答案解释了如何:How to read embedded resource text file

您还可以通过自己喜欢的搜索引擎找到大量示例和教程;尝试 "c# embedded resource"

对于 EF 迁移,我使用 sql,它存储在资源的数据层库中,然后像这样调用:

private string ReadSqlFile(string relativePath)
{
    var path = Path.Combine(AppContext.BaseDirectory, relativePath);
    return File.ReadAllText(path);
}

protected override void Up(MigrationBuilder migrationBuilder)
{
    //some migrations methods
    var script = ReadSqlFile("Migrations/DataMigration/AddNewCountryFieldToStudent.sql");
    migrationBuilder.Sql(script);
}

存储在单独的文件中非常有用。并且不要忘记更改 属性 以在本地复制。