码迷,mamicode.com
首页 > 数据库 > 详细

ADO.NET ORM数据库增删改查封装(工具一)

时间:2019-11-26 19:43:32      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:config   字符   creat   自动   prope   封装   each   属性   com   

约束

 

public abstract class BaseModel
{
  public int Id { get; set; }
}

 

连接字符串

public static readonly string Customers = ConfigurationManager.ConnectionStrings["Customers"].ToString();

通用数据库字符串

public class SqlBuilder<T> where T : BaseModel
{
  public static readonly string FindSql = null;
  public static readonly string DeleteSql = null;
  public static readonly string FindAllSql = null;
  public static readonly string UpdateSql = null;

  static SqlBuilder()
  {
    Type type = typeof(T);
    FindSql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}] where Id=@Id";

    DeleteSql = $"Delete from [{type.Name}] where Id=@Id"; ;
    FindAllSql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}]";
    UpdateSql = $"update [{type.Name}] set {string.Join(",", type.GetProperties().Where(a => !a.Name.Equals("Id")).Select(a => $"[{a.Name}]=@ {a.Name}"))} where Id =@Id";
  }
}

一:添加

public bool Add<T>(T t) where T : BaseModel
{
  Type type = typeof(T);
  object oCompany = Activator.CreateInstance(type);
  // Id 是自动增长的,sql语句中应该去除Id的字段
  // GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)  过滤掉继承自父类的属性
  string props = string.Join(",", type.GetProperties().Where(p => !p.Name.Equals("Id")).Select(a => $"[{a.Name}]"));//获取属性名不等于id的所有属性数组
  string paraValues = string.Join(",", type.GetProperties().Where(p => !p.Name.Equals("Id")).Select(a => $"@[{a.Name}]"));//获取属性名不等于id的所有参数化数组
  string sql = $"Insert [{type.Name}] ({props}) values({paraValues})";
  var parameters = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Select(item => new SqlParameter()
  {
    ParameterName = $"@{item.Name}",
    SqlValue = $"{item.GetValue(t)}"
  });
  //在拼接sql语句的时候,尽管ID 是Int类型,还是建议大家使用Sql语句参数化 (防止sql注入)
  using (SqlConnection connection = new SqlConnection(Customers))
  {
    SqlCommand sqlCommand = new SqlCommand(sql, connection);

    sqlCommand.Parameters.AddRange(parameters.ToArray());
    connection.Open();
    return sqlCommand.ExecuteNonQuery() > 0;
  }
}

二:删除

public bool Delete<T>(T t) where T : BaseModel
{
  Type type = t.GetType();
  string sql = SqlBuilder<T>.DeleteSql;
  //string sql = $"Delete from [{type.Name}] where Id=@Id";
  using (SqlConnection connection = new SqlConnection(Customers))
  {
    SqlCommand sqlCommand = new SqlCommand(sql, connection);
    sqlCommand.Parameters.Add(new SqlParameter("@Id", t.Id));
    connection.Open();
    return sqlCommand.ExecuteNonQuery() > 0;
  }
}

三:修改

public bool Update<T>(T t) where T : BaseModel
{
  Type type = typeof(T);
  object oCompany = Activator.CreateInstance(type);
  //string sql = $"update [{type.Name}] set {string.Join(",", type.GetProperties().Where(a => !a.Name.Equals("Id")).Select(a => $"[{a.Name}]=@ {a.Name}"))} where Id =@Id";
  string sql = SqlBuilder<T>.UpdateSql;
  var parameters = type.GetProperties().Select(item => new SqlParameter()
  {
    ParameterName = $"@{item.Name}",
    SqlValue = $"{item.GetValue(t)}"
  });
  //  在拼接sql语句的时候,尽管ID 是Int类型,还是建议大家使用Sql语句参数化防止sql注入)
  using (SqlConnection connection = new SqlConnection(Customers))
  {
    SqlCommand sqlCommand = new SqlCommand(sql, connection);

    sqlCommand.Parameters.AddRange(parameters.ToArray());
    connection.Open();
    return sqlCommand.ExecuteNonQuery() > 0;
  }
}

四:查询

//根据id查询

public T Find<T>(int id) where T : BaseModel
{
  Type type = typeof(T);
  object oCompany = Activator.CreateInstance(type);

  //string sql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}] where Id=@Id";

  string sql = SqlBuilder<T>.FindSql;


  //  在拼接sql语句的时候,尽管ID 是Int类型,还是建议大家使用Sql语句参数化 (防止sql注入)
  using (SqlConnection connection = new SqlConnection(Customers))
  {
    SqlCommand sqlCommand = new SqlCommand(sql, connection);
    sqlCommand.Parameters.Add(new SqlParameter("@Id", id));
    connection.Open();
    SqlDataReader reader = sqlCommand.ExecuteReader();
    if (reader.Read()) 
    {
      ReaderToList(type, oCompany, reader);
      return (T)oCompany;
    }
    else
    {
      return null;
    }
  }
}

//查询所有

public List<T> FindAll<T>() where T : BaseModel
{
  Type type = typeof(T);
  //string sql = $"SELECT {string.Join(",", type.GetProperties().Select(a => $"[{a.Name}]")) } FROM [{type.Name}]";

  string sql = SqlBuilder<T>.FindAllSql;

  using (SqlConnection connection = new SqlConnection(Customers))
  {
    SqlCommand sqlCommand = new SqlCommand(sql, connection);

    connection.Open();
    SqlDataReader reader = sqlCommand.ExecuteReader();
    List<T> datalist = new List<T>();
    while (reader.Read()) 
    {
      object oCompany = Activator.CreateInstance(type);
      ReaderToList(type, oCompany, reader);
      datalist.Add((T)oCompany);
    }
  return datalist;
  }
}

//私有函数封装通用代码,引用类型可以不用返回

private static void ReaderToList(Type type, object oCompany, SqlDataReader reader)
{
  foreach (var prop in type.GetProperties())
  {
    prop.SetValue(oCompany, reader[prop.Name] is DBNull ? null : reader[prop.Name]);
  }
}

ADO.NET ORM数据库增删改查封装(工具一)

标签:config   字符   creat   自动   prope   封装   each   属性   com   

原文地址:https://www.cnblogs.com/xutaostudy/p/11937485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!