.net由于新添加一个表就需要重新写一个BLL,操作数据库SQL,这样你会发现在制作大型项目的时候,您的时间都会花在建立模型上面去,这样就会影响您的工作效应,还有降低您的工作热情,还有就是增加您的出错次数,在深圳网站建设独占网络看来这些都可以减少,因为我们可以写的泛型就可以解决这些问题。
       那接下来我们就是教大家怎样建立一个泛型去操作数据库,增加的您的工作效率。       先我们建立一个新model,独占网络把这个叫为 
DuZhan.cs       我们在里面加入两个属性分别是 id,subject,所以我们的代码如下
public partial class Banner
 {
    public int id { set; get; }
    public string subject { set; get; }    
}
       建立好model之后我们就是把泛型的方法了。
       独占网络这里只是写一个添加的数据的方法,其它方法就是要让大家自己去写,如有不懂联系独占网络(http://www.sz886.com)
下面就是我们添加一个泛型数据库的方法了
public int Add<T>(T model)
{
  int result = 0;
    if (model != null)
      {
                //insert语句
                StringBuilder count = new StringBuilder();
                //参数的个数
                StringBuilder quest = new StringBuilder();
                var t = model.GetType();
                //得到泛型的信息
                PropertyInfo[] properties = t.GetProperties();
                if (properties.Length > 1)
                {
                    SqlParameter[] parameters = new SqlParameter[properties.Length - 1];
                    int i = 0;
                    //循环得到泛型信息
                    foreach (PropertyInfo property in properties)
                    {
                        if (i > 0)
                        {
                            if (!string.IsNullOrEmpty(count.ToString()))
                            {
                                count.Append(",");
                                quest.Append(",");
                            } 
                            //得到泛型里面的参数信息,如我们上面的id,subject,然后加入数据库操作语句中
                            count.Append(property.Name);
                            quest.Append("@" + property.Name);                                 
                            parameters[i - 1] = new SqlParameter("@" + property.Name, returnSqlDbType(property.PropertyType));
                            object value = property.GetValue(model, null);
                            parameters[i - 1].Value = value;
                        }
                        i++;
                    }
                    //得到Sql语句
                    string strsql = string.Format("insert into {0}({1}) values({2});select @@IDENTITY", typeof(T).Name, count.ToString(), quest.ToString());
                    object obj = DbHelperSQL.GetSingle(strsql, parameters);
                    if (obj == null)
                    {
                        return 0;
                    }
                    else
                    {
                        return Convert.ToInt32(obj);
                    }
                }
            }
            return result;
 } 
       这里我们就可以完成一个泛型的写法,下面我们就可以调用方法了添加的方法了 
Add<Model.DuZhan>(duzhan); 这样我们就可以完成操作了,如有不懂联系深圳网站建设:独占网络(http://www.sz886.com)