是否可以创建如下代码:
private static string GetInsertString<TDto>()
{
var type = typeof(TDto);
var properties = type.GetProperties().Where(Where);
var tableName = type.Name;
return string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
tableName,
string.Join(",", properties.Select(x => x.Name).ToArray()),
string.Join(",", properties.Select(x => string.Format("@{0}", x.Name.ToLower())).ToArray()));
}
可用于匿名类型,如:
var point = new { X = 13, Y = 7 };
附言:
输出为:
INSERT INTO Anonymous (X, Y) values (13, 7)
当然,您可能需要提供表名。
最佳答案
假设您使用的是.net 4.0或更高版本,则可以使用dynamic和ExpandoObject
如下:
private static string GetInsertString(dynamic obj)
{
var expando = (ExpandoObject)obj;
return string.Format("INSERT INTO {0} ({1}) VALUES ({2});",
"tableName",
string.Join(",", expando.Select(x => x.Key)),
string.Join(",", expando.Select(x => x.Value is string ? "'" + x.Value + "'" : x.Value.ToString())));
}
然后:
dynamic o = new ExpandoObject();
o.a = 10;
o.b = "hello";
var s = GetInsertString(o);
现在
s
是INSERT INTO tableName (a,b) VALUES (10,'hello');
。这只是一个草稿,您需要做一些工作才能得到一个正确的
insert
字符串。关于c# - 通用方法和匿名类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24403152/