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. 干货分享: 长达250页的Libvirt Qemu KVM的ppt,不实验无真相

    下载地址:Libvirt Qemu KVM 教程大全 http://files.cnblogs.com/popsuper1982/LibvirtQemuKVM.pptx 1. 概论 1.1 虚拟化的基 ...

  2. Vue 单文件原件 — vCheckBox

    简书原文 做东西一向奉行的是致简原则,一定要让使用者简单 这是我在使用 Vue 一段时间后尝试制作的一个小玩意 我希望可以做一堆这样的小玩意,随意组合使用,感觉挺好的 源码在最后 演示DEMO 示例: ...

  3. webpack 4.0 中 clean-webpack-plugin 的使用

    其实 clean-webpack-plugin 很容易知道它的作用,就是来清除文件的. 一般这个插件是配合 webpack -p 这条命令来使用,就是说在为生产环境编译文件的时候,先把 build或d ...

  4. Python程序里的注释和#号

    Python程序里的注释是很重要的.它们可以用自然语言告诉你某段代码的功能是什么.在你想要临时移除一段代码时,你还可以用注解的方式将这段代码临时禁用.接下来的练习将让你学会注释 : # A comme ...

  5. [Swift]LeetCode43. 字符串相乘 | Multiply Strings

    Given two non-negative integers num1 and num2 represented as strings, return the product of num1and  ...

  6. [Swift]LeetCode268. 缺失数字 | Missing Number

    Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missin ...

  7. [Swift]LeetCode532. 数组中的K-diff数对 | K-diff Pairs in an Array

    Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in t ...

  8. [Swift]LeetCode606. 根据二叉树创建字符串 | Construct String from Binary Tree

    You need to construct a string consists of parenthesis and integers from a binary tree with the preo ...

  9. [Swift]LeetCode629. K个逆序对数组 | K Inverse Pairs Array

    Given two integers n and k, find how many different arrays consist of numbers from 1 to n such that ...

  10. [Swift]LeetCode1003. 检查替换后的词是否有效 | Check If Word Is Valid After Substitutions

    We are given that the string "abc" is valid. From any valid string V, we may split V into ...