Example #1
0
        public string GetTableScript(Type entityType)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("create table ");
            sb.Append(entityType.Name);
            sb.Append("(");

            string keyName = null;

            bool   identity;
            object length;
            string dataType;
            bool   arrowNull;

            object[] objs;

            PropertyInfo[] pinfos = entityType.GetProperties();
            int            count  = entityType.GetProperties().Length;
            int            n      = 0;

            foreach (PropertyInfo pinfo in pinfos)
            {
                identity  = false;
                length    = null;
                dataType  = null;
                arrowNull = true;

                objs = pinfo.GetCustomAttributes(false);
                if (objs != null && objs.Length > 0)
                {
                    EntityAttribute cusatt = (EntityAttribute)objs[0];
                    if (cusatt.DisplayOnly)
                    {
                        count--;
                        continue;
                    }
                    if (cusatt.PrimaryKey)
                    {
                        keyName   = pinfo.Name;
                        arrowNull = false;
                    }
                    if (cusatt.Identity)
                    {
                        identity  = true;
                        arrowNull = false;
                    }
                    length   = cusatt.Length;
                    dataType = cusatt.DataType;
                }
                if (n > 0)
                {
                    sb.Append(",");
                }

                sb.Append("\r\n");
                sb.Append(pinfo.Name);
                sb.Append(" ");

                sb.Append(GetColumnType(pinfo, dataType, length));
                if (arrowNull)
                {
                    if (pinfo.PropertyType.IsGenericType)
                    {
                        if (pinfo.PropertyType.GetGenericTypeDefinition() != typeof(Nullable <>))
                        {
                            arrowNull = false;
                        }
                    }
                }
                if (!arrowNull)
                {
                    sb.Append(" not null");
                }
                else
                {
                    sb.Append(" null");
                }

                if (identity)
                {
                    sb.Append(" identity");
                }

                n++;
            }
            sb.Append("\r\n");
            if (keyName != null && keyName.Trim().Length > 0)
            {
                sb.Append(",");
                sb.Append("primary key(");
                sb.Append(keyName);
                sb.Append(")");
            }
            sb.Append(");");
            sb.Append("\r\n");
            sb.Append("\r\n");

            return(sb.ToString());
        }
Example #2
0
        public List <string> GetNewColumnsCommandTexts(DalLayerInfo dalInfo, Type entityType)
        {
            List <string> list = new List <string>();

            string    tableName = entityType.Name;
            DataTable dt        = null;

            // 检查表是否存在
            string sqlCheck = string.Format("SELECT TOP 1 * FROM {0};", tableName);

            try
            {
                dt = SqlHelper.ExecuteDataTable(dalInfo.Connection, dalInfo.Provider.CreateDataAdapter(), dalInfo.LongConnection, sqlCheck, null);
            }
            catch (Exception ex)
            { }
            if (dt == null)
            {
                // 表不存在
                list.Add(GetTableScript(entityType));
                return(list);
            }

            // 如果表已存在,则检查字段是否完整(通过字段名称判断)
            List <string> dtColumns = new List <string>();

            foreach (DataColumn column in dt.Columns)
            {
                dtColumns.Add(column.ColumnName.ToLower().Trim());
            }

            bool   primaryKey;
            bool   identity;
            object length;
            string dataType;
            bool   arrowNull;

            object[] objs;

            PropertyInfo[] pinfos = entityType.GetProperties();

            StringBuilder sb = new StringBuilder();

            foreach (PropertyInfo pinfo in pinfos)
            {
                if (dtColumns.Contains(pinfo.Name.ToLower().Trim()))
                {
                    continue;
                }

                sb.Remove(0, sb.Length);
                primaryKey = false;
                identity   = false;
                length     = null;
                dataType   = null;
                arrowNull  = true;

                objs = pinfo.GetCustomAttributes(false);
                if (objs != null && objs.Length > 0)
                {
                    EntityAttribute cusatt = (EntityAttribute)objs[0];
                    if (cusatt.DisplayOnly)
                    {
                        continue;
                    }
                    if (cusatt.PrimaryKey)
                    {
                        primaryKey = true;
                        arrowNull  = false;
                    }
                    if (cusatt.Identity)
                    {
                        identity  = true;
                        arrowNull = false;
                    }
                    length   = cusatt.Length;
                    dataType = cusatt.DataType;
                }

                sb.Append("alter table ");
                sb.Append(tableName);
                sb.Append(" add ");
                sb.Append(pinfo.Name);
                sb.Append(" ");
                sb.Append(GetColumnType(pinfo, dataType, length));
                if (arrowNull)
                {
                    if (pinfo.PropertyType.IsGenericType)
                    {
                        if (pinfo.PropertyType.GetGenericTypeDefinition() != typeof(Nullable <>))
                        {
                            arrowNull = false;
                        }
                    }
                }
                if (!arrowNull)
                {
                    sb.Append(" not null");
                    sb.Append(" default 0");
                }
                else
                {
                    sb.Append(" null");
                }

                if (identity)
                {
                    sb.Append(" identity(8,1)");
                }
                list.Add(sb.ToString());
                if (primaryKey)
                {
                    sb.Remove(0, sb.Length);
                    sb.Append("alter table ");
                    sb.Append(tableName);
                    sb.Append(" add constraint");
                    sb.Append(" pk_");
                    sb.Append(tableName);
                    sb.Append("_");
                    sb.Append(pinfo.Name);
                    sb.Append(" primary key(");
                    sb.Append(pinfo.Name);
                    sb.Append(")");
                    list.Add(sb.ToString());
                }
            }
            return(list);
        }
Example #3
0
        private void AddCmds(T entity, params string[] excludeColumns)
        {
            string[]      columns    = null;
            object[]      values     = null;
            object[]      objs       = null;
            List <string> listColumn = new List <string>();
            List <object> listValue  = new List <object>();

            PropertyInfo[] pis = typeof(T).GetProperties();

            for (int i = 0; i < pis.Length; i++)
            {
                // 排除插入列
                if (excludeColumns != null && excludeColumns.Length > 0)
                {
                    bool isExclude = false;
                    foreach (string excludeColumn in excludeColumns)
                    {
                        if (pis[i].Name.ToLower() == excludeColumn.Trim().ToLower())
                        {
                            isExclude = true;
                            break;
                        }
                    }
                    if (isExclude)
                    {
                        continue;
                    }
                }

                // 排除自增字段
                if (identityName != null)
                {
                    if (pis[i].Name.ToLower() == identityName.ToLower())
                    {
                        continue;
                    }
                }

                // 排除只显示列
                objs = pis[i].GetCustomAttributes(false);
                if (objs != null && objs.Length > 0)
                {
                    EntityAttribute cusatt = (EntityAttribute)objs[0];
                    if (cusatt.DisplayOnly)
                    {
                        continue;
                    }
                }

                object value = pis[i].GetValue(entity, null);
                if (value == null)
                {
                    continue;
                }
                listColumn.Add(pis[i].Name);
                listValue.Add(value);
            }
            if (listColumn.Count > 0)
            {
                columns = listColumn.ToArray();
                values  = listValue.ToArray();
            }
            if (columns == null)
            {
                return;
            }

            int cmdIndex;

            if (tranBuilder == null)
            {
                // 不是事务操作时,一次只操作一条语句
                this.listInsertObject.Clear();
                cmdIndex = this.cmdTexts.Count;
            }
            else
            {
                cmdIndex = tranBuilder.GetCmdTextsCount();

                // 在集合中站位,等创建脚本的时候再将内容填充
                tranBuilder.AddCommondType(CommandType.Text);
                tranBuilder.AddCmdText(null);
                tranBuilder.AddCmdParam(null);
            }

            listInsertObject.Add(
                new InsertBuilder <T> .InsertObject
            {
                CmdIndex      = cmdIndex,
                CmdText       = GetEntityCmd(cmdIndex, columns),
                CmdParamrters = GetEntityParams(entity, cmdIndex, columns, values),
            });
        }
Example #4
0
        private void AddUpdateObject(string keyName, T entity, Set_ updateSet, params string[] excludeColumns)
        {
            UpdateObject updateObject = new UpdateBuilder <T> .UpdateObject();

            if (keyName != null && keyName.Trim().Length > 0)
            {
                Dictionary <string, object> dit = new Dictionary <string, object>();
                Where_ tempWhere = new Where_();

                object[]        objs           = null;
                PropertyInfo [] pis            = typeof(T).GetProperties();
                bool            isKeyValueNull = true; // 主键值是否为null
                for (int i = 0; i < pis.Length; i++)
                {
                    if (excludeColumns != null && excludeColumns.Length > 0)
                    {
                        bool isExclude = false;
                        foreach (string excludeColumn in excludeColumns)
                        {
                            if (pis[i].Name.ToLower() == excludeColumn.Trim().ToLower())
                            {
                                isExclude = true;
                                break;
                            }
                        }
                        if (isExclude)
                        {
                            continue;
                        }
                    }

                    // 排除只显示列
                    objs = pis[i].GetCustomAttributes(false);
                    if (objs != null && objs.Length > 0)
                    {
                        EntityAttribute cusatt = (EntityAttribute)objs[0];
                        if (cusatt.DisplayOnly)
                        {
                            continue;
                        }
                    }
                    object value = pis[i].GetValue(entity, null);
                    if (value == null)
                    {
                        continue;
                    }

                    if (pis[i].Name.ToLower() == keyName.Trim().ToLower())
                    {
                        isKeyValueNull = false;
                        tempWhere.Equal(keyName, value);
                        continue;
                    }

                    dit.Add(pis[i].Name, value);
                }

                if (isKeyValueNull)
                {
                    throw new Exception(string.Format("属性{0}的值不能为null", keyName));
                }

                updateObject.Where         = tempWhere;
                updateObject.DitUpdateInfo = dit;
            }
            else if (updateSet != null)
            {
                updateObject.DitUpdateInfo = updateSet.DitUpdateInfo;
                updateObject.Where         = updateSet.MyWhere;
            }

            if (tranBuilder != null)
            {
                updateObject.CmdIndex = tranBuilder.GetCmdTextsCount();

                // 在集合中站位,等创建脚本的时候再将内容填充
                tranBuilder.AddCommondType(CommandType.Text);
                tranBuilder.AddCmdText(null);
                tranBuilder.AddCmdParam(null);
            }
            else
            {
                // 不是事务操作时,一次只操作一条语句
                this.listUpdateObject.Clear();
                updateObject.CmdIndex = listUpdateObject.Count;
            }
            this.listUpdateObject.Add(updateObject);
        }
Example #5
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        public bool Init(ref string msg)
        {
            try
            {
                this.initThreadId = Thread.CurrentThread.ManagedThreadId;

                this.dalInfo = new DalLayerInfo(this.connectionString, this.longConnection, this.provider);

                // 测试数据库连接
                if (string.IsNullOrEmpty(connectionString.Trim()))
                {
                    msg = "连接字符串为空";
                    return(false);
                }
                object obj = SqlHelper.ExecuteScalar(provider.CreateConnection(connectionString), false, "select 1");
                if (obj == null || obj == DBNull.Value)
                {
                    return(false);
                }
                if (Convert.ToInt32(obj) != 1)
                {
                    return(false);
                }

                // 获取表主键及自增字段
                object[] objs;
                object[] customAttributes;
                Type     attType = typeof(EntityAttribute);
                foreach (Type entityType in this.entityTypes)
                {
                    bool isEntity = false;
                    customAttributes = entityType.GetCustomAttributes(false);
                    if (customAttributes != null)
                    {
                        foreach (var a in customAttributes)
                        {
                            if (a.GetType() == attType)
                            {
                                isEntity = true;
                                break;
                            }
                        }
                    }
                    if (!isEntity)
                    {
                        continue;
                    }

                    // 找到目标次数
                    int findCount = 0;
                    foreach (PropertyInfo pinfo in entityType.GetProperties())
                    {
                        findCount = 0;
                        objs      = pinfo.GetCustomAttributes(false);
                        if (objs != null && objs.Length > 0)
                        {
                            EntityAttribute cusatt = (EntityAttribute)objs[0];
                            if (cusatt.PrimaryKey)
                            {
                                dicKeyNames.Add(entityType.Name, pinfo.Name);
                                findCount++;
                            }
                            if (cusatt.Identity)
                            {
                                dicIdentityNames.Add(entityType.Name, pinfo.Name);
                                findCount++;
                            }
                            if (findCount == 2)
                            {
                                break;
                            }
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }
        }
Example #6
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        public bool Init()
        {
            this.initThreadId = Thread.CurrentThread.ManagedThreadId;

            // 是否需要创建数据库
            bool isCreate = false;

            // 是否需要升级数据库
            bool isUpdate = false;

            // 获取配置文件版本号
            string dbDir        = Common.GetDir(dbPath);
            int    dbOldVersion = VersionManage.GetVersion(this.dbMark, dbDir);

            if (!File.Exists(dbPath))
            {
                isCreate = true;
            }
            else if (File.Exists(dbPath))
            {
                if (dbOldVersion < dbVersion)
                {
                    isUpdate = true;
                }
            }

            // 获取表主键及自增字段
            object[] objs;
            object[] customAttributes;
            Type     attType = typeof(EntityAttribute);

            foreach (Type entityType in this.entityTypes)
            {
                bool isEntity = false;
                customAttributes = entityType.GetCustomAttributes(false);
                if (customAttributes != null)
                {
                    foreach (var a in customAttributes)
                    {
                        if (a.GetType() == attType)
                        {
                            isEntity = true;
                            break;
                        }
                    }
                }
                if (!isEntity)
                {
                    continue;
                }

                // 找到目标次数
                int findCount = 0;
                foreach (PropertyInfo pinfo in entityType.GetProperties())
                {
                    findCount = 0;
                    objs      = pinfo.GetCustomAttributes(false);
                    if (objs != null && objs.Length > 0)
                    {
                        EntityAttribute cusatt = (EntityAttribute)objs[0];
                        if (cusatt.PrimaryKey)
                        {
                            dicKeyNames.Add(entityType.Name, pinfo.Name);
                            findCount++;
                        }
                        if (cusatt.Identity)
                        {
                            dicIdentityNames.Add(entityType.Name, pinfo.Name);
                            findCount++;
                        }
                        if (findCount == 2)
                        {
                            break;
                        }
                    }
                }
            }

            string connectionString = provider.GetConnectionString(dbPath, password);

            this.dalInfo = new DalLayerInfo(connectionString, this.longConnection, this.provider);
            if (isCreate)
            {
                // 新建数据库
                DBHelper dbHelper = new DBHelper();
                provider.CreateDatabase(dbPath, password);
                try
                {
                    Open();

                    // 创建表
                    dbHelper.CreateTables(dalInfo, this.entityTypes);

                    // 触发事件
                    if (this.createdDatabase != null)
                    {
                        this.createdDatabase();
                    }

                    Close();
                    if (dbOldVersion != dbVersion)
                    {
                        VersionManage.SetVersion(this.dbMark, dbDir, dbVersion);
                    }
                }
                catch (Exception ex)
                {
                    // 如果执行不成功则删除新建的数据库
                    if (File.Exists(dbPath))
                    {
                        Close();
                        try
                        {
                            File.Delete(dbPath);
                        }
                        catch { }
                    }
                    throw ex;
                }
            }
            else if (isUpdate)
            {
                // 升级数据库
                Open();
                if (this.upgradeDatabase != null)
                {
                    this.upgradeDatabase(dbOldVersion, dbVersion);
                }
                Close();
                if (dbOldVersion != dbVersion)
                {
                    VersionManage.SetVersion(this.dbMark, dbDir, dbVersion);
                }
            }

            return(true);
        }