是否可以创建这样的代码:
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()));
}
Run Code Online (Sandbox Code Playgroud)
适用于这样的匿名类型:
var point = new { X = 13, Y = 7 };
Run Code Online (Sandbox Code Playgroud)
PS:
输出将是:
INSERT INTO Anonymous (X, Y) values (13, 7)
Run Code Online (Sandbox Code Playgroud)
当然你可能想提供表名.
假设您使用 .net 4.0 或更高版本,您可以使用动态,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())));
}
Run Code Online (Sandbox Code Playgroud)
进而:
dynamic o = new ExpandoObject();
o.a = 10;
o.b = "hello";
var s = GetInsertString(o);
Run Code Online (Sandbox Code Playgroud)
现在s是INSERT INTO tableName (a,b) VALUES (10,'hello');。这只是一个草稿,您需要做一些工作才能获得正确的insert字符串。
| 归档时间: |
|
| 查看次数: |
1518 次 |
| 最近记录: |