C# 使用 Dapper 实现 SQLite 增删改查

Dapper 是一款非常不错的轻型 ORM 框架,使用起来非常方便,经常使用 EF 框架的人几乎感觉不到差别,下面是自己写的 Sqlite 通用帮助类;

1> 数据连接类;

    public class SQLiteBaseRepository
    {
        public static string DbFile
        {
            get {
                return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "VideoInfo.db");
            }
        }
        public static SQLiteConnection SimpleDbConnection()
        {
            
string connString = string.Format("Data Source={0};Password=******;", DbFile);
return new SQLiteConnection(connString); } }

2> 数据库访问帮助类 

    public class SQLiteDbHelper : IDisposable
    {
        /// 
        /// 常量;
        /// 
        const string INSERT_TABLE_ITEM_VALUE = "insert into {0} ({1}) values ({2})";
        const string DELETE_TABLE_WHERE = "delete from {0} where {1}";
        const string UPDATE_TABLE_EDITITEM = "update {0} set {1}";
        const string UPDATE_TABLE_EDITITEM_WHERE = "update {0} set {1} where {2}";
        const string Query_ITEM_TABLE_WHERE = "select {0} from {1} where {2}";

        private SQLiteConnection conn;
   
        public SQLiteDbHelper()
        {
            conn = openDataConnection();
        }
        /// 
        /// 打开数据库链接;
        /// 
        /// 
        private SQLiteConnection openDataConnection()
        {
            var conn = SqLiteBaseRepository.SimpleDbConnection();
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            return conn;
        }
        /// 
        /// 1.1 新增实体;
        /// 
        /// 实体类
        /// 实体
        /// 自增主键名称
        /// 
        public int Add(T model, string autoPrimaryKey = "id")
        {
            var insertSql = GetInsertSql(model,autoPrimaryKey);
            return conn.Execute(insertSql);
        }
        /// 
        /// 批量新增
        /// 
        /// 实休类
        /// 实体数据列表
        /// 自增主键名称
        /// 
        public int Adds(List models, string autoPrimaryKey = "id")
        {
            var type = typeof(T);
            int resultN = 0;
            var transaction = conn.BeginTransaction();
            try
            {
                models.ForEach(d =>
                {
                    var insertSql = GetInsertSql(d);
                    resultN += conn.Execute(insertSql);
                });
                transaction.Commit();
            }
            catch (Exception)
            {
                resultN = 0;
                transaction.Rollback();
            }
            return resultN;
        }
        /// 
        /// 删除
        /// 
        /// 实体类
        /// 删除条件
        /// 
        public int Delete(string where)
        {
            var type = typeof(T);
            string sqlStr = string.Format(DELETE_TABLE_WHERE, type.Name, where);
            return conn.Execute(sqlStr);
        }
        /// 
        /// 删除
        /// 
        /// 
        /// 
        /// 
        public int Delete(string tableName, string where)
        {
            string sqlStr = string.Format(DELETE_TABLE_WHERE,tableName,where);
            return conn.Execute(sqlStr);
        }
        /// 
        /// 修改; 
        /// 
        /// 实体 Type 
        /// 实体
        /// 修改条件
        /// 要修改的实休属性数组
        /// 
        public int Edit(T model, string where, params string[] attrs)
        {
            var sqlStr = GetUpdateSql(model, where, attrs);
            return conn.Execute(sqlStr);
        }

        /// 
        /// 根据条件查询单一实体;
        /// 
        /// 实体类
        /// 查询条件;
        /// 要查询的字段(传入 * 为查询所有字段。)
        /// 
        public T QeryByWhere(string where,params string[] attrs)
        {
            Type type = typeof(T);
            string item = attrs.Length == 1 && attrs[0] == "*" ? "*" : string.Join(",", attrs);
            var sqlStr = string.Format(Query_ITEM_TABLE_WHERE, item, type.Name, where);
            return conn.Query(sqlStr).FirstOrDefault();
        }
        
        /// 
        /// 根据条件查询符合条件的所有实体;
        /// 
        /// 
        /// 
        /// 
        public List QueryMultiByWhere(string where)
        {
            Type type = typeof(T);
            var sqlStr = string.Format(Query_ITEM_TABLE_WHERE, "*", type.Name, where);
            return conn.Query(sqlStr).ToList();
        }

        /// 
        /// 生成新增 sql 语句;
        /// 
        /// 
        /// 
        /// 
        /// 
        private string GetInsertSql(T model, string autoPrimaryKey = "id")
        {
            Type t = typeof(T);
            var propertyInfo = t.GetProperties();
            var proDic = propertyInfo.Where(s => !s.Name.Equals(autoPrimaryKey, StringComparison.InvariantCultureIgnoreCase))
                .Select(s => new
                {
                    key = s.Name,
                    value = GetValue(s, model)
                })
                .ToDictionary(s => s.key, s => s.value);
            proDic = proDic.Where(s => s.Value != "''").ToDictionary(s => s.Key, s => s.Value);
            var items = string.Join(",", proDic.Keys);
            var values = string.Join(",", proDic.Values);
            return string.Format(INSERT_TABLE_ITEM_VALUE,t.Name,items,values);
        }

        /// 
        /// 获取属性值;
        /// 
        /// 实体类
        /// 字段属性信息
        /// 实体
        /// 
        private string GetValue(PropertyInfo info,T model)
        {
            Type type = info.PropertyType;
            var tempStr = string.Empty;
            if (type == typeof(string))
            {
                tempStr = string.Format("'{0}'",info.GetValue(model));
                return tempStr;
            }
            if (type == typeof(DateTime))
            {
                tempStr = string.Format("'{0}'", ((DateTime)info.GetValue(model)).ToString("s"));
                return tempStr;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 
            {
                var types = type.GetGenericArguments();
                if (types[0] == typeof(DateTime))
                {
                    tempStr = string.Format("'{0}'", ((DateTime)info.GetValue(model)).ToString("s"));
                }
                tempStr = string.Format("'{0}'",info.GetValue(model));
                return tempStr;
            }  
            tempStr = info.GetValue(model).ToString();
            return tempStr;
        }

        /// 
        /// 生成更新 sql 语句;
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        private string GetUpdateSql(T model,string where, params string[] attrs)
        {
            Type t = typeof(T);
            var propertyInfo = t.GetProperties();
            var updateInfo = propertyInfo
                .Where(s => attrs.Contains(s.Name))
                .Select(s =>
                {
                    if (s.PropertyType == typeof(string))
                    {
                        return string.Format("{0}='{1}'",s.Name,s.GetValue(model));
                    }
                    if (s.PropertyType == typeof(DateTime))
                    {
                        return string.Format("{0}='{1}'",s.Name,((DateTime)s.GetValue(model)).ToString("s"));
                    }
                    if (s.PropertyType.IsGenericType && s.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        Type[] types = s.PropertyType.GetGenericArguments();
                        if (types[0] == typeof(DateTime))
                        {
                            return string.Format("{0}='{1}'", s.Name, ((DateTime)s.GetValue(model)).ToString("s"));
                        }
                        return string.Format("{0}={1}", s.Name, s.GetValue(model));
                    }
                    return string.Format("{0}={1}", s.Name, s.GetValue(model));
                })
                .ToArray();
            var setStr = string.Join(",",updateInfo);
            var sqlStr = string.Format(UPDATE_TABLE_EDITITEM_WHERE, t.Name, setStr, where);
            return sqlStr;
        }
        /// 
        /// 释放数据连接;
        /// 
        public void Dispose()
        {
            conn.Close();
            conn.Dispose();
        }

    }

 

转载于:https://www.cnblogs.com/llsfast/p/7883357.html

你可能感兴趣的:(C# 使用 Dapper 实现 SQLite 增删改查)