【问题标题】:C# SqlKata engine update query doesn't seem to executeC# SqlKata 引擎更新查询似乎没有执行
【发布时间】:2019-02-06 01:35:27
【问题描述】:

我有一个 C# 函数,旨在对 SQL Server 2016 表执行更新。为此,我正在利用 SqlKata 引擎。

我可能正在做一些非常简单/愚蠢的事情,我感觉我正在构建查询,但没有执行它?该文档仅显示了 UPDATE 语句的以下内容:

var query = new Query("Posts").WhereNull("AuthorId").AsUpdate(new {
    AuthorId = 10
});

我的更新稍微复杂一些,但基本上构造相同。我对某些属性使用动态对象,因此我强制 ToString 和 Convert.ToInt32 作为测试属性本身是否存在问题的一部分。日志记录表明这些值是正确的并且存在。

using (var connection = new SqlConnection(await RetrieveParameterStoreValue(ParameterStoreStrings.Database, true, context, environmentLogLevel)))
{
    var db = new QueryFactory(connection, new SqlServerCompiler())
    {
        // Log the compiled query to the console
        Logger = compiled =>
                        {
                            CreateCloudWatchLog($"Query = {compiled.ToString()}", context, LogLevel.Trace, environmentLogLevel);
                        }
    };

    string tableName = updateRequest.insite_request.objectReference.ToString();

    foreach (dynamic stockUpdate in updateRequest.insite_request.payload.items)
    {
        CreateCloudWatchLog($"Servername = {updateRequest.insite_request.payload.store_reference.ToString()} sku={stockUpdate.sku.ToString()} new soh={Convert.ToInt32(stockUpdate.committed_count)}", context, LogLevel.Error, environmentLogLevel);

        var query = db.Query(tableName)
                      .Where(new {
                            sku = stockUpdate.sku.ToString(),
                            ServerName = updateRequest.insite_request.payload.store_reference.ToString()
                            })
                      .AsUpdate(new
                            {
                                stock_on_hand = Convert.ToInt32(stockUpdate.committed_count)
                            });

        CreateCloudWatchLog($"stock update for {tableName}", context, LogLevel.Error, environmentLogLevel);
    }
}

我觉得我需要以某种方式调用构造的查询,但我不清楚如何。我有一些执行 SELECT 语句的 SqlKata 代码,为了调用它,我使用

 var results = query.Get();

但是我找不到任何关于类似调用的文档(沿着 query.Update 或类似的行?)为愚蠢的问题道歉。

作为参考,记录的输出没有显示任何执行迹象,表中的数据保持不变。

[Error] Servername = P777S001 sku=13643 new soh=10
[Error] stock update for InSiteClickCollect
[Error] Servername = P777S001 sku=13644 new soh=10
[Error] stock update for InSiteClickCollect
END RequestId: 2fec77e5-6a4e-4990-85e8-f541c9df6eef

【问题讨论】:

标签: c# .net sql-server sqlkata


【解决方案1】:

AsUpdate 方法不执行查询,它仅用于构建 sql 更新字符串

要执行您的查询,您必须执行以下操作。

  1. 使用db.Query() 而不是new Query(),其中dbQueryFactory 实例(它返回一个XQuery 实例,因此返回可执行Query)
  2. 使用UpdateInsertCount等...代替AsUpdateAsInsertAsCount

我强烈建议您阅读文档中的执行部分 https://sqlkata.com/docs/execution/

【讨论】:

    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多