如何在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
相关产品推荐
相关产品推荐

