zoukankan      html  css  js  c++  java
  • ORM反射

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Data.SqlClient;
    using Dapper;
    using System.Reflection;
    
    namespace DemoOrmHelper
    {
    public class OrmHelper<T> where T : class, new()
    {
    //连接数据库
    SqlConnection conn = new SqlConnection("Data Source=DESKTOP-O7U2DEC;Initial Catalog=B2C;Integrated Security=True");
    /// <summary>
    /// 使用反射,添加的Sql语句
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public int ExecuteNonQuary(T model)
    {
    //获取类型,字段不知道
    Type type = model.GetType();
    //实例化字符串
    StringBuilder stringBuilder = new StringBuilder();
    //拼接Sql语句,固定的
    stringBuilder.Append($"insert into {type.Name} values (");
    //获取字段属性的名称
    PropertyInfo[] properties = type.GetProperties();
    //循环拼接
    foreach (PropertyInfo item in properties)
    {
    if(item.Name != "ID")
    {
    stringBuilder.Append($"'{item.GetValue(model)}',");
    }
    }
    //去掉最后一个逗号
    string sql = $"{stringBuilder.ToString().TrimEnd(',')})";
    int code = conn.Execute(sql);
    return code;
    }
    /// <summary>
    /// 显示
    /// </summary>
    /// <returns></returns>
    public List<T> GetList()
    {
    //获取类型
    Type type = typeof(T);
    //Sql语句
    string sql = $"select * from {type.Name}";
    return conn.Query<T>(sql).ToList();
    }
    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="ID"></param>
    /// <returns></returns>
    public int Delete(int ID)
    {
    //获取类型
    Type type = typeof(T);
    string sql = $"delete from {type.Name} where ID={ID}";
    int code = conn.Execute(sql);
    return code;
    }
    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public int Update(T model)
    {
    //获取类型
    Type type = model.GetType();
    StringBuilder stringBuilder = new StringBuilder();
    //拼接Sql语句,固定的
    stringBuilder.Append($"update {type.Name} set ");
    //获取字段属性的名称
    PropertyInfo[] properties = type.GetProperties();
    //定义ID,修改的条件
    object id = null;
    foreach (PropertyInfo item in properties)
    {
    if(item.Name != "ID")
    {
    stringBuilder.Append($"{item.Name}='{item.GetValue(model)}',");
    }
    else
    {
    id = item.GetValue(model);
    }
    }
    //去掉最后一个逗号
    string sql = $"{stringBuilder.ToString().TrimEnd(',')} where ID={id}";
    int code = conn.Execute(sql);
    return code;
    }
    }
    }
  • 相关阅读:
    antd使用DatePicker组件出现TypeError: date.clone is not a function错误
    nrm解决npm install安装慢的问题
    antd pro显示自定义icon
    antd v4 使用后台返回的icon type的icon,并绑定事件
    复制textarea里输入的内容
    jsDelivr 缓存刷新小工具
    SweetAlert2网页弹窗---JAVASCRIPT弹窗
    Viewer.js 图片预览插件
    给你的网站加一个可爱的”躲猫猫“
    【Pyhton】随机漫步散点图
  • 原文地址:https://www.cnblogs.com/lina0621/p/13049442.html
Copyright © 2011-2022 走看看