C#.NET组织SQL查询并获得干净代码的最佳方法是什么

问题描述 投票:0回答:1

我和我的同事,我们面临一个问题。我们有几个SQL查询作为字符串。下面是一个示例:

    public class Query
{

    public static string CreditTransferId(string expectedValue, string table, int statusId, int messageTypeId, int destination103, int destination202, string StoreStatus202Id)
    {
        return $"SELECT top 1 Id from {table} where MessageId = '{expectedValue}' and FlowId=3 and StatusId={statusId} and MessageTypeId={messageTypeId} and " +
          $" Destination103={destination103} and Destination202={destination202} and StoreStatus103Id is null and StoreStatus202Id {StoreStatus202Id}";
    }
}

目前,我们从Query类中的方法将它们作为字符串返回。我们想重构代码使其干净,因为我们有一个带有3个以上参数的方法,无论如何还是很难使用。

您将如何处理?像上面的代码中那样,组织SQL查询的最干净的方法是什么?它需要很多参数?非常感谢任何可能改善我们代码当前状态的答案。

谢谢!

c# sql .net coding-style code-cleanup
1个回答
0
投票

动态SQL刚开始是一件很不好的事情,因为这些对象可以进行SQL注入,您应该使用参数化查询并返回字符串。

"eg: SELECT top 1 Id from [Table] where [MessageId] = @messageId"

所以您不需要传递任何值,您可以将这些值添加到SqlParamater的列表中>

表名可能没有意义,因为它与sql有关,因此可能只需将其添加到sql字符串中

这真的不需要额外的类,只需在调用它的地方创建sql变量,如果需要的话就在那里?

..或使用存储过程

..或使用实体框架

© www.soinside.com 2019 - 2024. All rights reserved.