You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# Switch表达式中动态生成带单引号的SQL查询条件

动态生成SQL中ActionType条件值的几种实现方式

方法1:嵌套Switch表达式

直接在字符串插值中嵌入小型Switch表达式,动态生成带单引号的ActionType值,无需额外变量:

string myQuery = source switch
{
    LogEntryType.IsInsert => "SELECT * FROM Table1;",
    LogEntryType.IsDelete or LogEntryType.IsUpdate =>
        $@"SELECT {thingsToSelect} FROM Table1 t WHERE t.ActionType = {source switch 
        { 
            LogEntryType.IsDelete => "'Deleted'", 
            LogEntryType.IsUpdate => "'Updated'" 
        }}",
    _ => throw new NotImplementedException(),
};

方法2:字典映射

提前定义枚举与目标字符串的映射关系,代码更整洁,适合枚举值较多的场景:

var actionTypeMap = new Dictionary<LogEntryType, string>
{
    { LogEntryType.IsDelete, "'Deleted'" },
    { LogEntryType.IsUpdate, "'Updated'" }
};

string myQuery = source switch
{
    LogEntryType.IsInsert => "SELECT * FROM Table1;",
    LogEntryType.IsDelete or LogEntryType.IsUpdate =>
        $@"SELECT {thingsToSelect} FROM Table1 t WHERE t.ActionType = {actionTypeMap[source]}",
    _ => throw new NotImplementedException(),
};

方法3:枚举扩展方法

给LogEntryType添加扩展方法,语义化更强,复用性高:

public static class LogEntryTypeExtensions
{
    public static string ToActionTypeString(this LogEntryType type)
    {
        return type switch
        {
            LogEntryType.IsDelete => "'Deleted'",
            LogEntryType.IsUpdate => "'Updated'",
            _ => throw new NotImplementedException()
        };
    }
}

// 使用时
string myQuery = source switch
{
    LogEntryType.IsInsert => "SELECT * FROM Table1;",
    LogEntryType.IsDelete or LogEntryType.IsUpdate =>
        $@"SELECT {thingsToSelect} FROM Table1 t WHERE t.ActionType = {source.ToActionTypeString()}",
    _ => throw new NotImplementedException(),
};

注意:生产环境中建议使用参数化查询避免SQL注入风险,比如通过SqlCommand添加参数,而非直接字符串拼接。

内容的提问来源于stack exchange,提问作者Bohn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:52:06