A表 id(int) name(nvarchar50) age(int) 1 张三 20 2 李四 23 3 王五 22 B表 num(int) nickname(nvarchar50) nianling(int) 现在我要写一个通用的方法.它要实现的功能是. 我给它一个A表实体.它根据id号将 id name age 1 张三 20 插入B表.
public T SetValueByS<S,T>(S source) where:T new() { T t = new T(); PropertyInfo[] spiArr = typeof(S).GetProperties(),tpiArr=typeof(T).GetProperties(); for(int i=0;i<spiArr.Length;i++) { tpiArr.SetValue(spiArr.GetValue(source),t); } return t; }大概意思,没测试
这跟你怎样“插”有关系,不可能什么都凭空制造,总要交代一下脚踩实地在哪里,哪怕你是踩在烽火轮上。比如说你使用Ado.NET,所谓常见的SqlHelper中的代码,那么大致可以这样写void RunSqlServerCommand(string sql, object obj, Action<SqlParameterCollection, object> setter) { using (var conn = GetMyDbConnection()) { var cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = System.Data.CommandType.Text; if (setter != null) setter(cmd.Parameters, obj); cmd.ExecuteNonQuery(); } }或者如果是一对象封装的方式,也可以使用事件方式来实现这里的setter。总之是把将来才需要扩展实现的流程作为回调方法。例如我们可以把setter作为一个static变量复用(省得在城里里到处重复写),然后可以这样在创建了一个新的object之后使用数据库class MyType { public string FieldA; public DateTime FieldB; public int FieldC; }public static Action<SqlParameterCollection, object> DeleteMyTypeObject = (ps, obj) => { ps.Add("@P", System.Data.SqlDbType.Int).Value = ((MyType)obj).FieldC; };void test() { MyType x = new MyType{ FieldC=1234}; RunSqlServerCommand("delete from abc where mc>@P", x, DeleteMyTypeObject); } 设计要扩展,但无需反射。 不过其实ado.net非常简单,我才懒得写SqlHelper呢。
id(int) name(nvarchar50) age(int)
1 张三 20
2 李四 23
3 王五 22
B表
num(int) nickname(nvarchar50) nianling(int)
现在我要写一个通用的方法.它要实现的功能是.
我给它一个A表实体.它根据id号将
id name age
1 张三 20
插入B表.
public T SetValueByS<S,T>(S source) where:T new()
{
T t = new T();
PropertyInfo[] spiArr = typeof(S).GetProperties(),tpiArr=typeof(T).GetProperties();
for(int i=0;i<spiArr.Length;i++)
{
tpiArr.SetValue(spiArr.GetValue(source),t);
}
return t;
}大概意思,没测试
{
using (var conn = GetMyDbConnection())
{
var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.Text;
if (setter != null)
setter(cmd.Parameters, obj);
cmd.ExecuteNonQuery();
}
}或者如果是一对象封装的方式,也可以使用事件方式来实现这里的setter。总之是把将来才需要扩展实现的流程作为回调方法。例如我们可以把setter作为一个static变量复用(省得在城里里到处重复写),然后可以这样在创建了一个新的object之后使用数据库class MyType
{
public string FieldA;
public DateTime FieldB;
public int FieldC;
}public static Action<SqlParameterCollection, object> DeleteMyTypeObject = (ps, obj) =>
{
ps.Add("@P", System.Data.SqlDbType.Int).Value = ((MyType)obj).FieldC;
};void test()
{
MyType x = new MyType{ FieldC=1234};
RunSqlServerCommand("delete from abc where mc>@P", x, DeleteMyTypeObject);
}
设计要扩展,但无需反射。
不过其实ado.net非常简单,我才懒得写SqlHelper呢。