/// <summary> /// 插入 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sqlStr"></param> /// <returns></returns> public virtual int Insert <T>(IDbConnection conn, T t) where T : BaseEntity { //获取实体信息 var entityInfo = new EntityMapping <T>(); var dataTableName = entityInfo.GetTableName(); //获取实体字段 var fields = entityInfo.GetFields(t).Where(l => l.Value != null && l.Value.ToString() != string.Empty); var strFieldNames = string.Join(',', fields.Select(l => l.Name)); var strFieldVals = string.Join(',', fields.Select(l => $"'{l.Value}'")); var sqlStr = $"insert into {dataTableName}({strFieldNames}) values ({strFieldVals})"; var data = SqlMapper.Execute(conn, sqlStr); return(data); }
/// <summary> /// 更新 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sqlStr"></param> /// <returns></returns> public virtual int Update <T>(IDbConnection conn, T t) where T : BaseEntity { //获取实体信息 var entityInfo = new EntityMapping <T>(); var dataTableName = entityInfo.GetTableName(); //获取实体字段 var fields = entityInfo.GetFields(t).Where(l => l.Value != null && l.Value.ToString() != string.Empty); var strFieldNames = string.Join(',', fields.Where(l => !l.IsKey).Select(l => l.Name)); var strFieldVals = string.Join(',', fields.Where(l => !l.IsKey).Select(l => $"'{l.Value}'")); //获取主键key var keyField = fields.FirstOrDefault(l => l.IsKey); if (keyField == null) { throw new Exception("key was not found!"); } var paramStr = string.Join(',', fields.Select(l => string.Format("{0}={1}", l.Name, l.Value is String ? $"'{l.Value}'" : l.Value))); var sqlStr = $"update {dataTableName} set {paramStr} where {keyField.Name}= '{keyField.Value}'"; var data = SqlMapper.Execute(conn, sqlStr); return(data); }