/// <summary>
        /// 获取插入语法
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override object InsertObject <T>(DbContextInner dbContext, T obj)
        {
            Type type   = obj.GetType();
            var  helper = dbContext.DBHelper;
            var  table  = TypeCache.GetTable(type);

            var    primaryKey = table.PrimaryKey;
            object id;

            if (primaryKey.KeepIdentity)
            {
                id = primaryKey.GetValue(obj);
            }
            else
            {
                string sequenceName = string.Format("{0}_sequence", table.TableName);
                var    sqlGetIndex  = string.Format("select {0}.nextval from dual", sequenceName);//oracle不能同时执行多条语句
                id = SqlStopWatch.ExecScalar(helper, sqlGetIndex);
                primaryKey.SetValue(obj, Convert.ChangeType(id, primaryKey.PropertyType));
            }

            var sql = GetInsertSql(dbContext, table, obj);

            //helper.SetParam(primaryKey.MapingName, id);
            SqlStopWatch.Execute(helper, sql);
            //var helper2 = helper as OracleHelper;
            //int id = helper2.Insert(sql,sequenceName);
            return(id);
        }
        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="tableName"></param>
        public override void CreateTable(DbContextInner dbContext, List <Attribute.FieldInnerAttribute> fields, string tableName)
        {
            var helper = dbContext.DBHelper;
            var lines  = new List <string>();
            //tableName = tableName.ToUpper();
            string        script     = string.Format("create table {0}(\r\n", tableName);
            List <string> list2      = new List <string>();
            string        primaryKey = "id";

            foreach (Attribute.FieldInnerAttribute item in fields)
            {
                if (item.IsPrimaryKey)
                {
                    primaryKey = item.MapingName;
                }
                var    columnType = GetDBColumnType(item.PropertyType);
                string nullStr    = item.NotNull ? "NOT NULL" : "";
                string str        = string.Format("{0} {1} {2} ", item.MapingName, item.ColumnType, nullStr);

                list2.Add(str);
            }
            script += string.Join(",\r\n", list2.ToArray());
            script += ")";
            string sequenceName   = string.Format("{0}_sequence", tableName);
            string triggerName    = string.Format("{0}_trigge", tableName);
            string sequenceScript = string.Format("Create Sequence {0} MINVALUE 1  MAXVALUE 999999999999 INCREMENT BY 1 START WITH 1 NOCACHE CYCLE", sequenceName);
            string triggerScript  = string.Format(@"
create or replace trigger {0}
  before insert on {1}   
  for each row
declare
  nextid number;
begin
  IF :new.{3} IS NULL or :new.{3}=0 THEN
    select {2}.nextval 
    into nextid
    from sys.dual;
    :new.{3}:=nextid;
  end if;
end ;", triggerName, tableName, sequenceName, primaryKey);

            lines.Add(sequenceScript);
            //defaultValues.Add(triggerScript); 暂不用触发器,不能编译成功
            //script += script2;
            helper.SetParam("script", script);
            helper.Run("sp_ExecuteScript");
            //helper.SetParam("script", sequenceScript);
            //helper.Run("sp_ExecuteScript");
            //helper.SetParam("script", triggerScript);
            //helper.Run("sp_ExecuteScript");

            foreach (string s in lines)
            {
                try
                {
                    helper.Execute(s);
                }
                catch (System.Exception ero) { };
            }
        }
Example #3
0
        bool PackageTrans(DbContextInner dbContext, TransMethod method, out string error, System.Data.IsolationLevel isolationLevel = System.Data.IsolationLevel.ReadCommitted)
        {
            error = "";
            var db = DBExtendFactory.CreateDBExtend(dbContext);

            db.BeginTran(isolationLevel);
            bool result;

            try
            {
                result = method(out error);
                if (!result)
                {
                    db.RollbackTran();
                    return(false);
                }
                db.CommitTran();
            }
            catch (Exception ero)
            {
                error = "提交事务时发生错误:" + ero.Message;
                db.RollbackTran();
                return(false);
            }
            return(result);
        }
Example #4
0
        /// <summary>
        /// 创建表脚本
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public override void CreateTable(DbContextInner dbContext, List <Attribute.FieldInnerAttribute> fields, string tableName)
        {
            var           helper        = dbContext.DBHelper;
            var           defaultValues = new List <string>();
            string        script        = string.Format("create table {0}(\r\n", KeyWordFormat(tableName));
            List <string> list2         = new List <string>();

            foreach (Attribute.FieldInnerAttribute item in fields)
            {
                string nullStr    = item.NotNull ? "NOT NULL" : "";
                var    columnType = GetDBColumnType(item.PropertyType);

                string str = string.Format("{0} {1} {2} ", KeyWordFormat(item.MapingName), item.ColumnType, nullStr);

                list2.Add(str);
            }
            script += string.Join(",\r\n", list2.ToArray());
            script += ") charset utf8 collate utf8_general_ci;";
            helper.Execute(script);
            foreach (string s in defaultValues)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    helper.Execute(s);
                }
            }
        }
Example #5
0
        public static ILambdaQuery <T> GetLambdaQuery <T>(this DbContext dbContext) where T : class
        {
            var helper = getDBHelper(dbContext);
            var db     = new DbContextInner(helper, new DBLocation());
            var query  = LambdaQueryFactory.CreateLambdaQuery <T>(db);

            return(query);
        }
Example #6
0
        internal override DbContextInner GetDbContext()
        {
            dbLocation.ManageName = ManageName;
            var helper    = DBConfigRegister.GetDBHelper(dbLocation);
            var dbContext = new DbContextInner(helper, dbLocation);

            dbContext.UseSharding = true;
            return(dbContext);
        }
        protected string GetInsertSql(DbContextInner dbContext, Attribute.TableInnerAttribute table, object obj, bool fillParame = true)
        {
            Type type      = obj.GetType();
            var  key       = string.Format("{0}_{1}", type, fillParame);
            var  helper    = dbContext.DBHelper;
            var  tableName = table.TableName;
            //var primaryKey = table.PrimaryKey;
            var typeArry = table.Fields;
            //var reflect = ReflectionHelper.GetInfo<T>();
            string sql;
            var    cached = insertSqlCache.TryGetValue(key, out sql);

            if (!cached)
            {
                sql = string.Format("insert into {0}(", KeyWordFormat(tableName));
            }
            string sql1 = "";
            string sql2 = "";

            foreach (Attribute.FieldInnerAttribute info in typeArry)
            {
                string name = info.MapingName;
                if (info.IsPrimaryKey && !info.KeepIdentity && DBType != DBType.ORACLE)
                {
                    continue;
                }
                object value = info.GetValue(obj);

                value = ObjectConvert.CheckNullValue(value, info.PropertyType);
                if (!cached)
                {
                    sql1 += string.Format("{0},", FieldNameFormat(info));
                    if (fillParame)
                    {
                        var par = GetParamName(name, "");
                        sql2 += string.Format("{0},", par);//@{0}
                    }
                }
                if (fillParame)
                {
                    helper.AddParam(name, value);
                }
            }
            if (!cached)
            {
                sql1 = sql1.Substring(0, sql1.Length - 1) + ") values";
                sql += sql1;
                if (fillParame)
                {
                    sql2 = sql2.Substring(0, sql2.Length - 1);
                    sql += "( " + sql2 + ")";
                }
                //sql = SqlFormat(sql);
                insertSqlCache.TryAdd(key, sql);
            }
            return(sql);
        }
Example #8
0
        public static IAbsDBExtend GetDBExtend(this DbContext dbContext)
        {
            var helper     = getDBHelper(dbContext);
            var dbContext2 = new DbContextInner(helper, new DBLocation()
            {
            });

            return(DBExtendFactory.CreateDBExtend(dbContext2));
        }
Example #9
0
 public MongoDBAdapter(DbContextInner _dbContext)
     : base(_dbContext)
 {
     if (!inited)
     {
         inited = true;
         //var serializer = new DateTimeSerializer(DateTimeKind.Local, BsonType.DateTime);
         //BsonSerializer.RegisterSerializer(typeof(DateTime), serializer);
     }
 }
        /// <summary>
        /// 批量插入,mysql不支持批量插入
        /// </summary>
        /// <param name="details"></param>
        /// <param name="keepIdentity"></param>
        public override void BatchInsert(DbContextInner dbContext, System.Collections.IList details, bool keepIdentity = false)
        {
            var helper = dbContext.DBHelper;

            foreach (var item in details)
            {
                helper.ClearParams();
                InsertObject(dbContext, item as IModel);
            }
        }
Example #11
0
        DbContextInner getDbContext(string manageName)
        {
            var dbLocation = new CRL.DBLocation()
            {
                DataAccessType = DataAccessType.Default, ManageType = GetType(), ManageName = manageName
            };
            var helper    = DBConfigRegister.GetDBHelper(dbLocation);
            var dbContext = new DbContextInner(helper, dbLocation);

            return(dbContext);
        }
Example #12
0
 /// <summary>
 /// lambda查询
 /// </summary>
 /// <param name="_dbContext"></param>
 /// <param name="_useTableAliasesName">查询是否生成表别名,在更新和删除时用</param>
 public LambdaQuery(DbContextInner _dbContext, bool _useTableAliasesName = true) : base()
 {
     __DbContext           = _dbContext;
     __MainType            = typeof(T);
     __DBAdapter           = DBAdapter.DBAdapterBase.GetDBAdapterBase(_dbContext);
     __UseTableAliasesName = _useTableAliasesName;
     GetPrefix(__MainType);
     __Visitor = new ExpressionVisitor(this);
     //TypeCache.SetDBAdapterCache(typeof(T), dBAdapter);
     QueryTableName = TypeCache.GetTableName(__MainType, __DbContext);
     startTime      = DateTime.Now;
 }
Example #13
0
        /// <summary>
        /// 根据数据库类型获取适配器
        /// </summary>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        public static DBAdapterBase GetDBAdapterBase(DbContextInner dbContext)
        {
            DBAdapterBase db = null;
            var           a  = DBAdapterBaseCache.TryGetValue(dbContext.DBHelper.CurrentDBType, out db);

            if (a)
            {
                return(db);
            }
            db = DBConfigRegister.GetDBAdapterBase(dbContext);
            DBAdapterBaseCache.Add(dbContext.DBHelper.CurrentDBType, db);
            return(db);
        }
Example #14
0
        /// <summary>
        /// 创建表脚本
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public override void CreateTable(DbContextInner dbContext, List <Attribute.FieldInnerAttribute> fields, string tableName)
        {
            var           defaultValues = new List <string>();
            string        script        = string.Format("create table [{0}] (\r\n", tableName);
            List <string> list2         = new List <string>();
            string        primaryKey    = "";

            foreach (Attribute.FieldInnerAttribute item in fields)
            {
                if (item.IsPrimaryKey)
                {
                    primaryKey = item.MapingName;
                }
                string nullStr = item.NotNull ? "NOT NULL" : "";
                string str     = string.Format("[{0}] {1} {2} ", item.MapingName, item.ColumnType, nullStr);
                list2.Add(str);
                //生成默认值语句
                if (!string.IsNullOrEmpty(item.DefaultValue))
                {
                    string v = string.Format("ALTER TABLE [dbo].[{0}] ADD  CONSTRAINT [DF_{0}_{1}]  DEFAULT ({2}) FOR [{1}]", tableName, item.MapingName, item.DefaultValue);
                    defaultValues.Add(v);
                }
            }
            script += string.Join(",\r\n", list2.ToArray());
            if (!string.IsNullOrEmpty(primaryKey))
            {
                script += string.Format(@" CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED 
(
	[{1}] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
", tableName, primaryKey);
            }
            script += ") ON [PRIMARY]";
            //var list3 = GetIndexScript();
            //defaultValues.AddRange(list3);
            var helper = dbContext.DBHelper;

            helper.Execute(script);
            foreach (string s in defaultValues)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    helper.Execute(s);
                }
            }
        }
Example #15
0
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="details"></param>
        /// <param name="keepIdentity"></param>
        public override void BatchInsert(DbContextInner dbContext, System.Collections.IList details, bool keepIdentity = false)
        {
            if (details.Count == 0)
            {
                return;
            }
            var type      = details[0].GetType();
            var table     = TypeCache.GetTable(type);
            var tableName = KeyWordFormat(table.TableName);
            var helper    = dbContext.DBHelper;

            var sb = new StringBuilder();

            GetSelectTop(sb, "*", b =>
            {
                b.Append(" from " + tableName + " where 1=0");
            }, "", 1);
            var sql       = sb.ToString();
            var tempTable = helper.ExecDataTable(sql);

            var typeArry = table.Fields;

            foreach (var item in details)
            {
                var dr = tempTable.NewRow();
                foreach (Attribute.FieldInnerAttribute info in typeArry)
                {
                    string name  = info.MapingName;
                    object value = info.GetValue(item);
                    if (!keepIdentity)
                    {
                        if (info.IsPrimaryKey)
                        {
                            continue;
                        }
                    }
                    var value2 = ObjectConvert.CheckNullValue(value, info.PropertyType);
                    dr[name] = value2;
                }
                tempTable.Rows.Add(dr);
            }
            helper.InsertFromDataTable(tempTable, tableName, keepIdentity);
        }
Example #16
0
        /// <summary>
        /// 获取插入语法
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override object InsertObject <T>(DbContextInner dbContext, T obj)
        {
            Type type       = obj.GetType();
            var  helper     = dbContext.DBHelper;
            var  table      = TypeCache.GetTable(type);
            var  primaryKey = table.PrimaryKey;
            var  sql        = GetInsertSql(dbContext, table, obj);

            if (primaryKey.KeepIdentity)
            {
                SqlStopWatch.Execute(helper, sql);
                return(primaryKey.GetValue(obj));
            }
            else
            {
                sql += ";SELECT LAST_INSERT_ID();";
                return(SqlStopWatch.ExecScalar(helper, sql));
            }
        }
Example #17
0
        public static LambdaQuery <T> CreateLambdaQuery <T>(DbContextInner _dbContext) where T : class
        {
            //var configBuilder = DBConfigRegister.current;
            var _DBType = _dbContext.DBHelper.CurrentDBType;

            if (_DBType != DBType.MongoDB)
            {
                return(new RelationLambdaQuery <T>(_dbContext));
            }
            var type = typeof(T);
            var a    = mongoQueryCreaters.TryGetValue(type, out object creater);

            if (!a)
            {
                var typeMongo   = DBConfigRegister.GetLambdaQueryType(DBType.MongoDB);
                var genericType = typeMongo.MakeGenericType(typeof(T));
                creater = Core.DynamicMethodHelper.CreateCtorFunc <Func <DbContextInner, LambdaQuery <T> > >(genericType, new Type[] { typeof(DbContextInner) });
                mongoQueryCreaters.TryAdd(type, creater);
            }
            var func = (Func <DbContextInner, LambdaQuery <T> >)creater;

            return(func(_dbContext));
        }
Example #18
0
 public override void BatchInsert(DbContextInner dbContext, System.Collections.IList details, bool keepIdentity = false)
 {
     throw new NotImplementedException();
 }
Example #19
0
 internal DbEntity(DbContextInner dbContext, Expression <Func <T, bool> > relationExp)
 {
     _dbContext   = dbContext;
     _relationExp = relationExp;
 }
 /// <summary>
 /// lambda查询
 /// </summary>
 /// <param name="_dbContext"></param>
 public MongoDBLambdaQuery(DbContextInner _dbContext)
     : base(_dbContext, false)
 {
 }
 /// <summary>
 /// lambda查询
 /// </summary>
 /// <param name="_dbContext"></param>
 /// <param name="_useTableAliasesName">查询是否生成表别名,在更新和删除时用</param>
 public RelationLambdaQuery(DbContextInner _dbContext, bool _useTableAliasesName = true)
     : base(_dbContext, _useTableAliasesName)
 {
 }
Example #22
0
 public DBAdapterBase(DbContextInner _dbContext)
 {
     //dbContext = _dbContext;
     //helper = dbContext.DBHelper;
     dbType = _dbContext.DBHelper.CurrentDBType;
 }
Example #23
0
 public MSSQL2000DBAdapter(DbContextInner _dbContext)
     : base(_dbContext)
 {
 }
Example #24
0
 /// <summary>
 /// 插入对象
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public abstract object InsertObject <T>(DbContextInner dbContext, T obj);
Example #25
0
 /// <summary>
 /// 批量插入方法
 /// </summary>
 /// <param name="details"></param>
 /// <param name="keepIdentity">否保持自增主键</param>
 public abstract void BatchInsert(DbContextInner dbContext, System.Collections.IList details, bool keepIdentity = false);
Example #26
0
 /// <summary>
 /// 创建表
 /// </summary>
 /// <param name="fields"></param>
 /// <param name="tableName"></param>
 public abstract void CreateTable(DbContextInner dbContext, List <Attribute.FieldInnerAttribute> fields, string tableName);
Example #27
0
 public DbSet(string name, DbContextInner dbContext)
 {
     _dbContext = dbContext;
     _dbContext._DbSets.Add(name, this);
 }
Example #28
0
        //static System.Collections.Concurrent.ConcurrentDictionary <string, DataTable> cacheTables = new System.Collections.Concurrent.ConcurrentDictionary<string, DataTable>();
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="details"></param>
        /// <param name="keepIdentity"></param>
        public override void BatchInsert(DbContextInner dbContext, System.Collections.IList details, bool keepIdentity = false)
        {
            if (details.Count == 0)
            {
                return;
            }
            var type      = details[0].GetType();
            var table     = TypeCache.GetTable(type);
            var tableName = KeyWordFormat(table.TableName);
            var helper    = dbContext.DBHelper;
            //DataTable tempTable;
            //var key = string.Format("{0}_{1}", dbContext.DBHelper.DatabaseName, type.Name);
            //if (!cacheTables.ContainsKey(key))
            //{
            //    var sb = new StringBuilder();
            //    GetSelectTop(sb,"*", b=>
            //    {
            //        b.Append(" from " + tableName + " where 1=0");
            //    }, "", 1);
            //    var sql = sb.ToString();
            //    var tempTable2 = helper.ExecDataTable(sql);
            //    //cacheTables.TryAdd(key, tempTable2);//暂每次动态查询
            //    tempTable = tempTable2.Clone();//创建一个副本
            //}
            //else
            //{
            //    tempTable = cacheTables[key].Clone();
            //}
            var sb = new StringBuilder();

            GetSelectTop(sb, "*", b =>
            {
                b.Append(" from " + tableName + " where 1=0");
            }, "", 1);
            var sql       = sb.ToString();
            var tempTable = helper.ExecDataTable(sql);

            ////字段顺序得和表一至,不然插入出错
            //DataTable tempTable = new DataTable() { TableName = tableName };
            //foreach (var f in table.Fields)
            //{
            //    var column = new DataColumn() { ColumnName = f.MapingName, DataType = f.PropertyType, AllowDBNull = true };
            //    tempTable.Columns.Add(column);
            //}
            var typeArry = table.Fields;

            foreach (var item in details)
            {
                DataRow dr = tempTable.NewRow();
                foreach (Attribute.FieldInnerAttribute info in typeArry)
                {
                    string name  = info.MapingName;
                    object value = info.GetValue(item);
                    if (!keepIdentity)
                    {
                        if (info.IsPrimaryKey)
                        {
                            continue;
                        }
                    }
                    var value2 = ObjectConvert.CheckNullValue(value, info.PropertyType);
                    dr[name] = value2;
                }
                tempTable.Rows.Add(dr);
            }
            helper.InsertFromDataTable(tempTable, tableName, keepIdentity);
        }
Example #29
0
 public MongoDBExt(DbContextInner _dbContext)
     : base(_dbContext)
 {
 }
 public ORACLEDBAdapter(DbContextInner _dbContext)
     : base(_dbContext)
 {
 }