using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using MODEL;
using Dapper;

namespace DAL
{
    public class ORMHelper: ConfigurationBaseDal
    {
        #region 批量查询
        /// <summary>
        /// 数据库链接字符串
        /// </summary>
        private static string SQLStr = "Data Source=.;Initial Catalog=Students;Persist Security Info=True;User ID=sa;Password=root;";
        public   List<T> GetAll<T>() where T : class, new()//定义一个泛型,和泛型约束
        {
            string sqlFormat = "select {0} from {1}";//定义基结构
            Type type = typeof(T);//反射实体类
            var pi = type.GetProperties();
            string csStr = string.Join(",", pi.Select(o => o.Name));
            sqlFormat = string.Format(sqlFormat, csStr, type.Name);
            SqlConnection conn = new SqlConnection(SQLStr);
            DataTable dt = new DataTable();
            try
            {
                SqlDataAdapter dap = new SqlDataAdapter(sqlFormat, conn);//一次性加载数据库中所有属性,可以脱离链接进行操作,返回一个dataset对象
                dap.Fill(dt);
                List<T> list = new List<T>();
                ; i < dt.Rows.Count; i++)
                {
                    T t = new T();
                    foreach (var  pro in pi)
                    {
                        if (dt.Columns.Contains(pro.Name))
                        {
                            if (!(dt.Rows[i][pro.Name] is DBNull))//判断是否为空
                            {
                                pro.SetValue(t, dt.Rows[i][pro.Name]);
                            }
                        }
                    }
                    list.Add(t);
                }
                return list;
            }
            catch (Exception ex)
            {

                throw ex ;
            }
        }
        #endregion

        #region 条件查询
        /// <summary>
        /// 根据条件查询,也许有问题,讲师返回的是泛型T,而我经过改进返回的数值类型是datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public  List<OrmsTable> GetModel<T>(OrmsTable model) where T : class, new()
        {
            string whereStr = "";
            string sqlStr = "select {0} from {1} where 1=1 {2}";
            Type typeT = typeof(T);
            PropertyInfo[] pi = typeT.GetProperties();
            string[] pNames = pi.Select(o => o.Name).ToArray();
            string fieldStr = string.Join(",", pNames);//ID,name,chinese,enume"
            pNames = pi.Where(p => p.GetCustomAttribute(typeof(KeyAttribute), false) != null).Select(o => o.Name).ToArray();
            )
            {
                whereStr = ],model.Zhuangtai);//例如:and id=1;
            }
            sqlStr = string.Format(sqlStr, fieldStr, typeT.Name, whereStr);//select ID,name,chinese,enume from Class1 where 1=1  and ID = 1 

             var dt =CurrentDbConn.Query<OrmsTable>(sqlStr)?.ToList();
            return dt;
        }
        #endregion

        #region 添加数据
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        //public static int Insert<T>(T model)
        //{
        //    string sqlStr = "insert into {0}({1}) values({2})";
        //    string tbNameStr = string.Empty;
        //    string feildNameStr = string.Empty;
        //    string valStr = string.Empty;

        //    Type typeT = typeof(T);
        //    tbNameStr = typeT.Name;
        //    PropertyInfo[] pis = typeT.GetProperties();
        //    feildNameStr = string.Join(",", pis.Where(p => p.GetCustomAttribute(typeof(KeyAttribute), false) == null).Select(o => o.Name));
        //    valStr = string.Join(",", pis.Where(p => p.GetCustomAttribute(typeof(KeyAttribute), false) == null).Select(o => "@" + o.Name));
        //    sqlStr = string.Format(sqlStr, tbNameStr, feildNameStr, valStr);
        //    List<SqlParameter> pList = new List<SqlParameter>();
        //    foreach (PropertyInfo p in pis)
        //    {
        //        object obj = p.GetValue(model);
        //        string pName = "@" + p.Name;
        //        SqlParameter sp = new SqlParameter(pName, obj);
        //        pList.Add(sp);
        //    }
        //    return DBHelper.ExecuteNonQuery(sqlStr, pList.ToArray());
        //}
        public  int Insert<T>(T Param) where T : class, new()
        {
            var t = typeof(T);
            string sql = "insert into " + t.Name + " values('";
            foreach (var item in t.GetProperties())
            {
                if(item.PropertyType.Name!="Int32")
                {
                    sql += item.GetValue(Param) + "','";
                }
                else
                {
                    sql += item.GetValue(Param) + ",";
                }
            }
           ,(sql.Length)-);
            st += "')";
            return CurrentDbConn.Execute(st);
        }
        #endregion

        #region 删除
        public  int Delete<T>(T model)
        {
            string sqlStr = "delete from {0} where 1=1 {1}";
            string strWhere = "";
            Type typeT = typeof(T);
            string tbName = typeT.Name;//声明一个变量用来存贮表的名字
            var pi = typeT.GetProperties();
            var pKey = pi.Where(p => p.GetCustomAttribute(typeof(KeyAttribute), false) != null);
            List<SqlParameter> pList = new List<SqlParameter>();
            )
            {
                PropertyInfo pK = pKey.First();
                strWhere = string.Format(" and {0} = @{0}", pK.Name);
                pList.Add(new SqlParameter("@" + pK.Name, pK.GetValue(model)));
            }
            sqlStr = string.Format(sqlStr, tbName, strWhere);
            return CurrentDbConn.Execute(sqlStr, pList.ToArray());
        }
        #endregion

        public  bool Upt<T>(T t) where T : class, new()
        {
            bool ret = false;
            try
            {
                string str = "";
                string str1 = "";
                string sql = "update {0} set {1} where {2}";
                Type tp = typeof(T);
                foreach (var i in tp.GetProperties())
                {
                    var ty = i.PropertyType;
                    var tu = i.GetCustomAttributes(false);
                    )
                    {
                        str1 += " " + i.Name + "='" + i.GetValue(t) + "'";
                    }
                    else
                    {
                        switch (ty.Name)
                        {
                            case "Int32":
                                str += " " + i.Name + " ='" + i.GetValue(t) + "' ,";
                                break;
                            case "String":
                                str += " " + i.Name + " ='" + i.GetValue(t).ToString() + "' ,";
                                break;
                        }
                    }
                }
                str = str.Substring(, str.Length - );
                sql = string.Format(sql, tp.Name, str, str1);
                using (SqlConnection conn = new SqlConnection(SQLStr))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.ExecuteNonQuery();
                        ret = true;
                    }
                }
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return ret;
        }
    }
}
dapper的连接

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
   public  class ConfigurationBaseDal: ParDal
    {
        private string _systemCenterStr = System.Configuration.ConfigurationManager.ConnectionStrings["DbConter"].ConnectionString;

        //这是一个锁为了防止并发的发生
        private object obj = new object();

        private IDbConnection _systemCenterDbConn;

        //定义一个字段
        //利用单例模式来执行连接数据库
        public override IDbConnection CurrentDbConn
        {
            get
            {
                //判断是否与数据库连接
                if (_systemCenterDbConn == null)
                {
                    lock (obj)
                    {
                        if (_systemCenterDbConn == null)
                        {
                            _systemCenterDbConn = new SqlConnection(_systemCenterStr);
                        }
                    }
                }
                return _systemCenterDbConn;
            }
        }
    }
}

ORM的增删查的更多相关文章

  1. [开源]无sql之旅-Chloe.ORM之增删查改

    扯淡 这是一款轻量.高效的.NET C#数据库访问框架(ORM).查询接口借鉴 Linq(但不支持 Linq).借助 lambda 表达式,可以完全用面向对象的方式就能轻松执行多表连接查询.分组查询. ...

  2. 4.在MVC中使用仓储模式进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...

  3. SSH框架的多表查询和增删查改 (方法一)中

    原创作品,允许转载,转载时请务必标明作者信息和声明本文章==>http://www.cnblogs.com/zhu520/p/7774144.html   这边文章是接的刚刚前一遍的基础上敲的  ...

  4. SSH框架的多表查询(方法二)增删查改

     必须声明本文章==>http://www.cnblogs.com/zhu520/p/7773133.html  一:在前一个方法(http://www.cnblogs.com/zhu520/p ...

  5. SSH2 增删查改实例

    (一)引入包 (共73个,不一定都需要,但是我的项目是这么多,经过调试,没有包冲突) (二)创建数据库表 建立数据库octtest,并创建user表,表里面一共4个字段:id,姓,名,年龄. 语句如下 ...

  6. mybatis、spring、mysql、maven实现简单增删查改

    之前写过的mybatis博客作为学习mybatis.spring还是不太合适. 现在找到一个不错的例子,首先将这个完整的mybatis增删查改例子在本地上实现出来,然后再进行学习. 项目结构与运行结果 ...

  7. 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  8. 3.EF 6.0 Code-First实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-entity-framework-5-0-code- ...

  9. 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

随机推荐

  1. gym 101628

    前几天感冒了三天没怎么写题...今天好很多了打个三星场找点手感. 不行啊我好菜啊.只会8个..补题的话,再说吧.G题感觉值得一补. 补了G,K不想写B不会. 说实话这个三星场还是很新人向的,知识点也蛮 ...

  2. Redis安装完整步骤

    安装: 1.获取redis资源 wget http://download.redis.io/releases/redis-4.0.8.tar.gz 2.解压 tar xzvf redis-4.0.8. ...

  3. CIKM 2012 papers to be downloaded

    http://dl.acm.org/citation.cfm?id=2398426   http://dl.acm.org/citation.cfm?id=2396825   http://dl.ac ...

  4. Java的几种设计模式

    java的设计模式大体上分为三大类: 创建型模式(5种):工厂方法模式,抽象工厂模式,单例模式,建造者模式,原型模式. 结构型模式(7种):适配器模式,装饰器模式,代理模式,外观模式,桥接模式,组合模 ...

  5. data自定义属性获取方法和设置

    <!--原生获取方法--> <div data-id="id=1"></div> <script> //js原生获取方法 var i ...

  6. [Swift]LeetCode186. 翻转字符串中的单词 II $ Reverse Words in a String II

    Given an input string, reverse the string word by word. A word is defined as a sequence of non-space ...

  7. [Swift]LeetCode273. 整数转换英文表示 | Integer to English Words

    Convert a non-negative integer to its english words representation. Given input is guaranteed to be ...

  8. Linux指令装图像化界面

    1.对yum进行配置安装.//这是重点 [root@localhost ~]# yum groupinstall "GNOME Desktop" "Graphical A ...

  9. php内核一些常识

    整个PHP环境和Zend环境会涉及多个全局变量,下面是几个比较重要的: php_core_globals core_globals(main/php_globals.h) ==> PG PHP调 ...

  10. MySQL优化之推荐使用规范

    一.基础规范 使用InnoDB存储引擎支持事务.行级锁.并发性能更好.CPU及内存缓存页优化使得资源利用率更高 推荐使用utf8mb4字符集无需转码,无乱码风险, 支持emoji表情以及部分不常见汉字 ...