构建一个
SQL
查询来传递。
我有这样的东西:
enum LogEntryType
{
IsUpdate,
IsInsert,
IsDelete
}
//
//
//
string thingsToSelect = "*";
var source = LogEntryType.IsDelete;
string myQuery = source switch
{
LogEntryType.IsInsert => "SELECT * FROM Table1;",
LogEntryType.IsDelete or LogEntryType.IsUpdate =>
$@"SELECT {thingsToSelect} FROM Table1 t WHERE t.ActionType = 'Deleted' ",
_ => throw new NotImplementedException(),
};
注意
'Deleted'
用单引号引起来,因为我想将它传递给 SQL
,如下所示:
SELECT * FROM Table1 t WHERE t.ActionType = 'Deleted'
但是我希望
'Deleted'
部分更加动态,这样如果开关使用 LogEntryType.IsDelete
那么它应该是 'Deleted'
并且当开关是 LogEntryType.IsUpdate
时它应该是 'Updated'
所以这两个之一作为最终这两个 switch 语句的语句。
SELECT * FROM Table1 t WHERE t.ActionType = 'Deleted'
SELECT * FROM Table1 t WHERE t.ActionType = 'Updated'
但是我在嵌入这个逻辑时遇到了麻烦,该逻辑也可以将其包裹在该 switch 语句的单行中的单引号中。这就是我需要帮助的地方。
您可以使用三元运算符,或者通过剪切枚举名称,但我倾向于单独编写它们。
$@"SELECT {thingsToSelect} FROM Table1 t WHERE t.ActionType = '{(source == LogEntryType.IsDelete ? "Delete" : "Update")}' "
$@"SELECT {thingsToSelect} FROM Table1 t WHERE t.ActionType = '{source.ToString().Substring(2)}' "