ORMHelp
public class ORMHelp
{
public void Insert(object table)
{
Type type = table.GetType();
//定義一個字典來存放表中字段和值的對應序列
Dictionary<string, string> columValue = new Dictionary<string, string>();
StringBuilder SqlStr=new StringBuilder();
SqlStr.Append("insert into ");
//得到表名子
TableAttribute temp = (TableAttribute)type.GetCustomAttributes(false).First();
SqlStr.Append(temp.TableName);
SqlStr.Append("(");
PropertyInfo[] Propertys=type.GetPropertIEs();
foreach (var item in Propertys)
{
object[] attributes = item.GetCustomAttributes(false);
foreach (var item1 in attributes)
{
//獲得相應屬性的值
string value= table.GetType().InvokeMember(item.Name, System.Reflection.BindingFlags.GetProperty, null, table, null).ToString();
ColumAttribute colum = item1 as ColumAttribute;
if (colum != null)
{
columValue.Add(colum.ColumName,value);
}
}
}
//拼插入操作字符串
foreach (var item in columValue)
{
SqlStr.Append(item.Key);
SqlStr.Append(",");
}
SqlStr.Remove(SqlStr.Length-1, 1);
SqlStr.Append(") values('");
foreach (var item in columValue)
{
SqlStr.Append(item.Value);
SqlStr.Append("','");
}
SqlStr.Remove(SqlStr.Length - 2, 2);
SqlStr.Append(")");
Console.WriteLine(SqlStr.ToString());
}
}
SqlStr中的內容為insert into User(userID,UserName) values('1','lfm')
前端使用代碼:
static void Main(string[] args)
{
ORMHelp o = new ORMHelp();
User u = new User() { UserID=1,UserName="lfm"};
o.Insert(u);
}
本文配套源碼