C#基于IDbConnection扩展简单实现ORM关系映射

本文介绍了作者使用C#基于IDbConnection扩展实现的简单ORM关系映射,包括查询、添加、修改和删除操作。欢迎讨论更优实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是根据我个人自己的理解然后实现的,如果能有更好的实现方式希望各位能指点一二
查询方法

public static IEnumerable<T> Query<T>(this IDbConnection conn, string    sql, params SqlParameter[] parameters)
       {
           using (conn)
           {
               List<T> dataList = new List<T>();
               Type t = typeof(T);
               SqlCommand comm = conn.CreateCommand() as SqlCommand;
               comm.CommandText = sql;
               comm.Parameters.AddRange(parameters);
               conn.Open();
               SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
               while (reader.Read())
               {
                   dataList.Add((T)GetClassProperty(reader, t));
               }
               reader.Close();
               return dataList;
           }
       }
    public static IEnumerable<T> Query<T>(this IDbConnection conn) where T : class
        {
            using (conn)
            {
                List<T> dataList = new List<T>();
                Type t = typeof(T);
                PropertyInfo[] propertyInfo = t.GetProperties();
                SqlCommand comm = conn.CreateCommand() as SqlCommand;
                string tableName = GetDataTableNameByAttr(t);
                StringBuilder cloumnStr = new StringBuilder();
                foreach (PropertyInfo property in propertyInfo)
                {
                    if (property.PropertyType.IsConstructedGenericType || (!property.PropertyType.IsPrimitive && !property.PropertyType.Equals(typeof(string)) && property.PropertyType.IsClass)) continue;
                    cloumnStr.Append(property.Name + ",");
                }
                comm.CommandText = string.Format("SELECT {0} FROM {1}", cloumnStr.ToString().TrimEnd(','), tableName);
                conn.Open();
                SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
                while (reader.Read())
                {
                    dataList.Add((T)GetClassProperty(reader, t));
                }
                reader.Close();
                return data
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值