实用的实体类

来源:互联网 发布:单片机课设 编辑:程序博客网 时间:2024/05/21 11:25
using System;
using System.Collections.Generic;
using System.Text;

//这里是字段模板
namespace HuibaiTech.Model
{
    /// <summary>
    /// 一个字段的两个属性 值 和名称,中文名称
    /// </summary>
    public class Field
    {
        public string FiledName;
        public object FiledValue;
        public string ChineseName;


        public Field()
        {
            FiledValue = DBNull.Value;
            FiledName = "";
            ChineseName = "";


        }


        public Field(object Fvalue, string name)
        {
            FiledName = name; FiledValue = Fvalue; ChineseName = "";


        }
        public Field(object Fvalue, string name, string chineseName)
        {
            FiledName = name; FiledValue = Fvalue; ChineseName = chineseName;


        }


    }

}

//表模板基类

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace HuibaiTech.Model
{
    public abstract class BaseModel 
 {
            public readonly string[] filedNames ;
            public readonly string TableName;
            public readonly int FieldLenth;
            protected readonly Dictionary<string, Field> dic = new Dictionary<string, Field>();
            public Dictionary<string, object> GetValuesDic()
            {
                Dictionary<string, object> dicRet = new Dictionary<string, object>();
                foreach (Field a in dic.Values)
                {
                    dicRet.Add(a.FiledName, a.FiledValue);
                }
                return dicRet;


            }
        /// <summary>
        /// 获取实体类成员字段类的变量名称
        /// </summary>
        /// <param name="ModelType"></param>
        /// <returns></returns>
    protected   List<string> GetFieldMemVarName(Type ModelType)
            {
                List<string> retList = new List<string>();


                FieldInfo[] mis = ModelType.GetFields();
                Type FieldType = typeof(Field);
                foreach (FieldInfo a in mis)
                {
                    if (a.FieldType.Name==(FieldType.Name))
                    {
                        retList.Add(a.Name);
                      
                    }
                }
                return retList; 
            }


  
   
 
    /// <summary>
    /// 设置模板类Field成员变量的值 用于初始化中 要求变量名称与实体表字段名称相同
    /// </summary>
    /// <param name="ModelType">实体类类型</param>
    /// <param name="Obj">实体类本身 传this就可以</param>
  protected  void SetFieldMemVarValue(Type ModelType,object Obj)
    {
      
        FieldInfo[] mis = ModelType.GetFields();
        Type FieldType = typeof(Field);
        foreach (FieldInfo a in mis)
        {
            if (a.FieldType.Name == (FieldType.Name))
            {
                a.SetValue(Obj,dic[a.Name]);


            }
        }
     
    }


 
            protected BaseModel(string[] FieldNames,string tableName)
            {
                filedNames = FieldNames;
                TableName = tableName;
                FieldLenth = filedNames.Length;
                foreach (string a in filedNames)
                {


                    dic.Add(a, new Field(DBNull.Value, a));


                }
                BindFieldDic();




            }
     /// <summary>
     /// 把字段和dic中的裝載的字段綁定
     /// </summary>
            public abstract void BindFieldDic();
      
            public Field this[string index]
            {


                get
                {
                    return dic[index];
                }
                set
                {
                    dic[index] = value;


                }




            
            }
    }
}

//创建一个车信息表的例子

using System;
using System.Collections.Generic;
using System.Text;


namespace  HuibaiTech.Model
{
  public  class CarInformation:BaseModel
    {


      public CarInformation()
          : base(new string[] { "CarCode","MemberID", "CurrentMileage", "NextMileage", "LatestOilChangeTime", 
            "NextOilChangeTime", "Brand", "Color", "MemCardID" }, "CarInformation")
      { 
        
      }
      public override void BindFieldDic()
      {
          //CarCode = dic["CarCode"];
          //MemCardID = dic["MemCardID"];
          //CurrentMileage = dic["CurrentMileage"];
          //NextMileage = dic["NextMileage"];


          //LatestOilChangeTime = dic["LatestOilChangeTime"];
          //NextOilChangeTime = dic["NextOilChangeTime"];
          //Brand = dic["Brand"];
          //Color = dic["Color"];
          SetFieldMemVarValue(typeof(CarInformation),this);


      }
      /// <summary>
      /// 会员ID 不是会员卡号 用于散客
      /// </summary>
      public Field MemberID;
      /// <summary>
      /// 车牌号
      /// </summary>
      public Field CarCode ;
      /// <summary>
      /// 绑定的会员卡号
      /// </summary>
      public Field MemCardID ;
      /// <summary>
      /// 当前里程数
      /// </summary>
      public Field CurrentMileage ;
      /// <summary>
      /// 下次换油里程数
      /// </summary>
      public Field NextMileage;
/// <summary>
/// 最近换油时间
/// </summary>
      public Field LatestOilChangeTime ;
      /// <summary>
      /// 下次换油时间
      /// </summary>
      public Field NextOilChangeTime;
      /// <summary>
      /// 车品牌
      /// </summary>
      public Field Brand ;
      /// <summary>
      /// 车颜色
      /// </summary>
      public Field Color;
    }
}



//匹配的数据层  使用它需要修改的就是数据库执行函数

using System;
using System.Collections.Generic;


using System.Text;
using System.Data;


using System.Data.OleDb;
using HuibaiTech.Model;
using HuibaiTech.DBUtility;
namespace HuibaiTech.OleDbDAL
{
    /// <summary>
    /// 所有表的基类  
    /// </summary>
public    class TableBaseDal
    {
       /// <summary>
       /// 像表插入数据
       /// </summary>
       /// <param name="dicData">字段名称和值一对</param>
       /// <param name="tableName">表名</param>
       /// <returns></returns>
        public int InsertIntoTable(Dictionary<string, object> dicData,string tableName)
        {
          
            string strSqlHead =string.Format( "insert into  {0} ( ",tableName);
            string strTail = "values(";


            List<OleDbParameter> list = new List<OleDbParameter>();
            foreach (string a in dicData.Keys)
            {
                if (dicData[a] == null||dicData[a]==DBNull.Value||dicData[a].ToString()=="")
                    continue;
              
                strSqlHead += String.Format("{0},", a);
                strTail += string.Format("@{0},", a);
                
                list.Add(DbHelperOleDb.MakeInParameter(a,dicData[a]));
            }


             OleDbParameter[] paramts = list.ToArray();


            //去掉最后一个逗号
             strSqlHead = strSqlHead.Remove(strSqlHead.Length - 1);
             strTail = strTail.Remove(strTail.Length - 1);
            //加上右括号
            strSqlHead += ")";
             strTail += ")";


             strSqlHead = String.Format("  {0}{1}",strSqlHead,strTail);
          
            return DbHelperOleDb.ExecuteSql( strSqlHead, paramts);




        }
        /// <summary>
        /// 根据条件获取表数据
        /// </summary>
        /// <param name="SelectWhere">where后的条件句</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public DataTable GetTableData(string SelectWhere,string tableName)
        {
            string SqlStr =string.Format( "select * from {0} where {1} ",tableName,SelectWhere);
      
            return DbHelperOleDb.Query(SqlStr).Tables[0];
        
        }
    /// <summary>
    /// 根据形如 where id=@id or memcardId=@memcardId 过滤获取数据
    /// </summary>
    /// <param name="Wherefields"></param>
    /// <param name="tableName">表名</param>
    /// <param name="AndOr">true 为and false 为 or</param>
    /// <returns></returns>
        public DataTable GetTableData(List<Field> Wherefields, string tableName,bool AndOr)
        {
            string LogOrAnd="";
      
            if (AndOr)
            {
                LogOrAnd = " and ";
            }
            else
            {
                LogOrAnd = " or  ";
            }


            string strSql = string.Format("select * from {0} where   ", tableName);


            List<OleDbParameter> list = new List<OleDbParameter>();
            foreach (Field a in Wherefields)
            {
                
                list.Add(DbHelperOleDb.MakeInParameter(a.FiledName,a.FiledValue));


                strSql += String.Format("{0}=@{0} {1}", a.FiledName, LogOrAnd);


            }
            strSql = strSql.Remove(strSql.Length - LogOrAnd.Length);


            return DbHelperOleDb.Query(strSql, list.ToArray()).Tables[0];


        }
    //更新到数据库
        public bool UpdateToDb(DataTable dt, string tableName)
        {
            string SqlStr = string.Format("select * from {0} where 1=0 ", tableName);
            return  DbHelperOleDb.UpdateToDb(dt,SqlStr);
 
        
        }


   /// <summary>
   /// 删除
   /// </summary>
   /// <param name="deleteWhere">符合sql语句语法</param>
   /// <param name="tableName"></param>
   /// <returns></returns>
        public int DeleteTableRows(string deleteWhere, string tableName)
        {
            string SqlStr = string.Format("delete from {0} where {1}",tableName , deleteWhere);
              
            return    DbHelperOleDb.ExecuteSql(SqlStr, new OleDbParameter[]{});
        
        }
        public int DeleteTableRows( string tableName, Field whereField)
        {
            string SqlStr = string.Format("delete from {0} where {1}=@{1}", tableName, whereField.FiledName);


            return DbHelperOleDb.ExecuteSql(SqlStr, new OleDbParameter[] {DbHelperOleDb.MakeInParameter(whereField.FiledName,whereField.FiledValue) });


        }
    /// <summary>
    /// 不能将空值更新到数据库
    /// </summary>
    /// <param name="dic"></param>
    /// <param name="whereField"></param>
    /// <param name="tableName"></param>
    /// <returns></returns>
        public int UpdateTableData(Dictionary<string, object> dic, Field whereField,string tableName)
        {


            string strSql = string.Format("update {0} set  ", tableName);
            List<OleDbParameter> list = new List<OleDbParameter>();
            foreach (string a in dic.Keys)
            {
                if (dic[a]== null || dic[a].ToString().Length==0)
                    continue;
                list.Add(DbHelperOleDb.MakeInParameter(a, dic[a]));
                if ("ID" == a)
                    continue;
                strSql += String.Format("{0}=@{0},", a);


            }


            //将条件字段装入参数集
            OleDbParameter parmTemp = new OleDbParameter();
            //专用  "MoGuiVale"   为了解决在参数集中出现条件字段值 和参数字段集中存在条件字段参数的冲突
            //也可以解决在使用时 用一个字段的新旧值来更新的问题
            //参数名和字段名可以不相同 
            const string whereParamName = "MokuZiVale";


            parmTemp = DbHelperOleDb.MakeInParameter(whereParamName, whereField.FiledValue);
            list.Add(parmTemp);
            OleDbParameter[] paramts = list.ToArray();


            //去掉最后一个逗号
            strSql = strSql.Remove(strSql.Length - 1);




            strSql += String.Format("  where {0}= @{1}", whereField.FiledName, whereParamName);


            return DbHelperOleDb.ExecuteSql(strSql, paramts);
        
        
        }




        public int UpdateTableData(Dictionary<string, object> dic, Field[] WhereFields, string tableName)
        {


            string strSql = string.Format("update {0} set  ", tableName);


            List<OleDbParameter> list = new List<OleDbParameter>();
            foreach (string a in dic.Keys)
            {
                if (dic[a] == null || dic[a] == DBNull.Value)
                    continue;
                list.Add(DbHelperOleDb.MakeInParameter(a, dic[a]));
                if ("ID" == a)
                    continue;
                strSql += String.Format("{0}=@{0},", a);


            }
        
            //去掉最后一个逗号
            strSql = strSql.Remove(strSql.Length - 1);


            //将条件字段装入参数集
        //    OleDbParameter parmTemp = new OleDbParameter();
            //专用  "MoGuiVale"   为了解决在参数集中出现条件字段值 和参数字段集中存在条件字段参数的冲突
            //也可以解决在使用时 用一个字段的新旧值来更新的问题
            //参数名和字段名可以不相同 
            const string whereParamName = "MokuZiVale";
            int i = 0;
            strSql += "  where";
            foreach (Field parms in WhereFields)
            {


                strSql += String.Format("   {0}= @{1} and ", parms.FiledName, String.Format("{0}{1}", whereParamName, i));
                list.Add(DbHelperOleDb.MakeInParameter(String.Format("{0}{1}", whereParamName, i),parms.FiledValue));
                i++;
            
            }


            strSql= strSql.Remove(strSql.Length - 4, 4);
            OleDbParameter[] paramts = list.ToArray();
            return DbHelperOleDb.ExecuteSql(strSql, paramts);




        }
    }
}


0 0