自已动手做一个最简版的Nhibernate

最近动手做一个项目,结果项目延期了,自己分析一下,大部分的时间花在了与项目中数据的持久化那一块了,觉得自己有点吃亏,原因是自己对Nhiberate不太熟,经常出错,
并且,一个很小的项目,所有的东西加起来都不到1M,却因为引用了Nhibernate,加上Nhiberante必须用的几个DLLL很整个工程变得很大,觉得有点过分,所以想来想去,就决定做一个自己版的Nhiberate,这是第一个版本的代码,刚刚写出来,

其中的东西,都集中在了静态类里了,还在要类中实现自己的load,update,insert,delete语句,使用有点麻烦,不过好在自己心里清楚, 用得放心,调试的舒心. 

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Reflection;
using  System.Data.SqlClient;
using  System.Windows.Forms;
using  System.Data;
using  System.Collections;

namespace  learn.MyReflector
{
   
public class Task
    
{

       
private int m_id;
       
private DateTime m_arrtime;
       
private string m_name;

       
public int Id get return m_id; } set { m_id = value; } }
       
public DateTime ArrTime get return m_arrtime; } set { m_arrtime = value; } }
       
public string Name get return m_name; } set { m_name = value; } }

       
public string connstr;//数据库的连接字符串

       
public override string ToString()
       
{
           
return "learn.MyReflector.Task";
       }


       
public void Load()
       
{
           SqlConnection con 
= new SqlConnection(connstr);  
           
string[] tpcls = this.ToString().Split('.');
           Array.Reverse(tpcls);
           
string tablename = tpcls[0];
           DataRow dr
=null;  
           List
<string> provalue = new List<string>();

           ArrayList ar 
= new ArrayList();
           
object[] arvalue = null;
           
try
           
{
               SqlCommand com 
= new SqlCommand();
               com.Connection 
= con;
               com.CommandText 
="select * from "+tablename+" where id='"+Id.ToString()+"'";
               SqlDataAdapter sda
=new SqlDataAdapter();
               sda.SelectCommand
=com;
               DataSet ds
=new DataSet();
               sda.Fill(ds);
               DataTable dt
=ds.Tables[0];
               

               
if (dt.Rows.Count > 0)
                   dr 
= dt.Rows[0];
               
else
                   
return;

               
for (int i = 0; i < dt.Columns.Count; i++)
                   ar.Add(dr[i]);

               arvalue
=new object[ar.Count];
               ar.CopyTo(arvalue);
               MyReflectorTest.SetValue(ToString(), 
this, arvalue);

          
//   MyReflectorTest.SetValue(ToString(), this, provalue);
 
           }

           
catch (Exception ex)
           
{
               MessageBox.Show(ex.Message);
           }

           
finally { con.Close(); }
       }


       
public void Create()
       
{
           SqlConnection con 
= new SqlConnection(connstr);
           
try
           
{

               SqlCommand com 
= new SqlCommand();
               com.Connection 
= con;
               com.CommandText 
= MyReflector.MyReflectorTest.GetInserSql(this.ToString(), this);
               
if (con.State == ConnectionState.Closed)
                   con.Open();
               
this.Id = Convert.ToInt32(com.ExecuteScalar());
           }

           
catch (Exception ex)
           
{
               MessageBox.Show(ex.Message);
           }

           
finally { con.Close(); }
       }


       
public void Update()
       
{
           SqlConnection con 
= new SqlConnection(connstr);
           
try
           
{

               SqlCommand com 
= new SqlCommand();
               com.Connection 
= con;
               com.CommandText 
= MyReflector.MyReflectorTest.GetUpdateSql(this.ToString(), this);
               
if (con.State == ConnectionState.Closed)
                   con.Open();
               
this.Id = Convert.ToInt32(com.ExecuteScalar());
           }

           
catch (Exception ex)
           
{
               MessageBox.Show(ex.Message);
           }

           
finally { con.Close(); }
       }


    }




    
public static  class MyReflectorTest
    
{
        
public static void Start(
            
string clsname, object tarobj,
            List
<string> proName,
             List
<string> proValue)
        
{
            Assembly asm 
= Assembly.GetExecutingAssembly();
            System.Type tasktype 
= asm.GetType(clsname);

            PropertyInfo[] proinfo 
= tasktype.GetProperties();

            
foreach (PropertyInfo pi in proinfo)
            
{
                proName.Add(pi.Name);
                
//System.Console.WriteLine(pi.Name);
                
//System.Console.WriteLine(pi.PropertyType.ToString());
                proValue.Add(pi.GetValue(tarobj, new object[] { }).ToString());
            }


        }



        
public static string GetInserSql(string clsname, object tarobj)
        
{
            
string[] tpcls = clsname.Split('.');
            Array.Reverse(tpcls);
            
string tablename = tpcls[0];
            StringBuilder sb 
= new StringBuilder();
            sb.Append(
"insert into "+tablename+"(");
            List
<string> proName = new List<string>(); //属性名
            List<string> provalue = new List<string>() ;//属性值
            Start(clsname, tarobj,proName,  provalue);

            
int idpos = 0;//id在返回的字符串中的位置
            StringBuilder sb2 = new StringBuilder();

            
for (int i = 0; i < proName.Count; i++)
            
{
                
if (proName[i].ToLower() != "id")
                    sb2.Append(proName[i] 
+ ",");
                
else
                    idpos 
= i;
            }

            

            sb.Append( sb2.ToString().Substring(
0, sb2.ToString().Length - 1)); 
            sb.Append(
") values(");


            StringBuilder sb3 
= new StringBuilder();
            
for (int j = 0; j < provalue.Count; j++)
            
{
                
if (j != idpos)
                    sb3.Append(
"'" + provalue[j] + "',");
            }

            

           
            sb .Append(sb3.ToString().Substring(
0, sb3.ToString().Length - 1));
            sb.Append(
");select @@IDENTITY");
            
return sb.ToString(); 
        }


        
public static string GetUpdateSql(string clsname, object tarobj)
        
{
            
string[] tpcls = clsname.Split('.');
            Array.Reverse(tpcls);
            
string tablename = tpcls[0];
            
string conditionstr = "";
            StringBuilder sb 
= new StringBuilder();
            sb.Append(
"update  " + tablename + " set ");
            List
<string> proName = new List<string>(); //属性名
            List<string> provalue = new List<string>();//属性值
            Start(clsname, tarobj, proName, provalue); 

            StringBuilder sb2 
= new StringBuilder();
            
for (int i = 0; i < proName.Count; i++)
                
if (proName[i].ToLower() != "id")
                    sb2.Append(proName[i] 
+ "='" + provalue[i] + "',");
                
else
                    conditionstr 
= " where id='" + provalue[i] + "'";  

            sb.Append(sb2.ToString().Substring(
0, sb2.ToString().Length - 1));
            sb.Append(conditionstr); 
            
return sb.ToString(); 

        }


        
public static string GetDelSql(string clsname, object tarobj)
        
{

            
string[] tpcls = clsname.Split('.');
            Array.Reverse(tpcls);
            
string tablename = tpcls[0];
            
string conditionstr = "";

            StringBuilder sb 
= new StringBuilder();
            sb.Append(
"delete from  " + tablename  );
            List
<string> proName = new List<string>(); //属性名
            List<string> provalue = new List<string>();//属性值
            Start(clsname, tarobj, proName, provalue);

           
            
for (int i = 0; i < proName.Count; i++)
                
if (proName[i].ToLower() == "id")
                    conditionstr 
= " where id='" + provalue[i] + "'"

            
            sb.Append(conditionstr);
            
return sb.ToString(); 

        }


        
public static string GetCreateTabSql(string clsname, object tarobj)
        
{
            Hashtable ht 
= new Hashtable();
            ht.Add(
"System.Int32"," int ,");
            ht.Add(
"System.String"" nvarchar(50),");
            ht.Add(
"System.DateTime"" DateTime ,");
           
            
string[] tpcls = clsname.Split('.');
            Array.Reverse(tpcls);
            
string tablename = tpcls[0];
           

            StringBuilder sb 
= new StringBuilder();
            sb.Append(
"create table  " + tablename + " ( id int identity(1,1),");
            List
<string> proName = new List<string>(); //属性名
            List<string> proType = new List<string>();//属性值
            GetProNameAndType(clsname, tarobj, proName, proType);


            StringBuilder sb2 
= new StringBuilder();
            
for (int i = 0; i < proName.Count; i++)
            
{
                
if (proName[i].ToLower() != "id")
                    sb2.Append(proName[i] 
+ ht[proType[i]] );
            }


            sb.Append(sb2.ToString().Substring(
0,sb2.ToString().Length-1)+")");
            
return sb.ToString(); 
        }



      
/*  public static string GetSearchStr()
        {
            string[] tpcls = clsname.Split('.');
            Array.Reverse(tpcls);
            string tablename = tpcls[0];


            StringBuilder sb = new StringBuilder();
            //select * from task where id='9'
            sb.Append("select * from  " + tablename + " where id=''");
            List<string> proName = new List<string>(); //属性名
            List<string> proType = new List<string>();//属性值
            GetProNameAndType(clsname, tarobj, proName, proType);


            StringBuilder sb2 = new StringBuilder();
            for (int i = 0; i < proName.Count; i++)
            {
                if (proName[i].ToLower() != "id")
                    sb2.Append(proName[i] + ht[proType[i]]);
            }

            sb.Append(sb2.ToString().Substring(0, sb2.ToString().Length - 1) + ")");
            return sb.ToString(); 
        }
*/



        
public static void SetValue(
            
string clsname, object tarobj, 
            
object[] proValue)
        
{
            Assembly asm 
= Assembly.GetExecutingAssembly();
            System.Type tasktype 
= asm.GetType(clsname);

            PropertyInfo[] proinfo 
= tasktype.GetProperties();

            
int i = 0;
            
foreach (PropertyInfo pi in proinfo)
            
{
                
try
                
{
                    pi.SetValue(tarobj, proValue[i], 
null);
                    i
++;
                }

                
catch (Exception ex)
                
{
                    MessageBox.Show(ex.Message);
                }

            }

        }


        
public static void GetProNameAndType(
          
string clsname, object tarobj,
          List
<string> proName,
           List
<string> proType)
        
{
            Assembly asm 
= Assembly.GetExecutingAssembly();
            System.Type tasktype 
= asm.GetType(clsname);

            PropertyInfo[] proinfo 
= tasktype.GetProperties();

            
foreach (PropertyInfo pi in proinfo)
            
{
                proName.Add(pi.Name);
                proType.Add(pi.PropertyType.ToString()); 
            }


        }



      



    }


}

调用代码

 


            MyReflector.Task mytask 
=   new  learn.MyReflector.Task();
            mytask.ArrTime 
=  DateTime.Now;
            mytask.Id 
=   120 ;
            mytask.Name 
=   " test " ;


            
// MyReflector.MyReflectorTest tp = new learn.MyReflector.MyReflectorTest();
            
// tp.Start(mytask.ToString(), mytask);
            
// learn.MyReflector.MyReflectorTest.Start(mytask.ToString(), mytask);
            System.Console.WriteLine
            (
            learn.MyReflector.MyReflectorTest.GetInserSql(mytask.ToString(), mytask)
            );

            System.Console.WriteLine
         (
         learn.MyReflector.MyReflectorTest.GetUpdateSql(mytask.ToString(), mytask)
         );

            System.Console.WriteLine
      (
      learn.MyReflector.MyReflectorTest.GetDelSql(mytask.ToString(), mytask)
      );

            System.Console.WriteLine
     (
     learn.MyReflector.MyReflectorTest.GetCreateTabSql(mytask.ToString(), mytask)
     );



            mytask.connstr 
=   @" server=.cxy2;uid=sa;pwd=cxy;database=test " ;
            mytask.Create();

            Console.WriteLine(mytask.Id.ToString());


            MyReflector.Task btask 
=   new  learn.MyReflector.Task();
            btask.connstr 
=  mytask.connstr;
            btask.Id 
=  mytask.Id;

            btask.ArrTime 
=  DateTime.Parse( " 2007/07/07 12:56:23 " );
            btask.Name 
=   " cxy " ;
            btask.Update();

            MyReflector.Task cc 
=   new  learn.MyReflector.Task();
            cc.connstr 
=  btask.connstr;
            cc.Id 
=   3 ;
            cc.Load();
            Console.WriteLine(cc.ArrTime.ToString());
            
            
string   bb  =  System.Console.ReadLine();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值