我已经实现了一种使用名称而不是数字的字符串格式这是我的 sql 字符串:
string sqlStr = @"select * from Table1 t1
where t1.field1 = @Field1 and IsActive = 1";
int F1 = 12;
sqlStr = sqlStr.NamedStringFormatSQL(new
{
Field1 = F1
});
这是格式化程序的代码:
public static Dictionary<string, object> AnonymousToDictionary(object value)
{
Dictionary<string, object> dic = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
if (value != null)
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(value))
{
object obj2 = descriptor.GetValue(value);
dic.Add(descriptor.Name, obj2);
}
}
return dic;
}
public static string NamedStringFormatSQL(this string aString, object replacements)
{
Dictionary<string, object> keyValues = AnonymousToDictionary(replacements);
foreach (var item in keyValues)
{
string val = item.Value == null ? "null" : item.Value.ToString();
aString = aString.Replace("@" + item.Key, val);
}
return aString;
}