/// <summary>
        /// 在事务中删除数据表中满足指定条件的数据.
        /// </summary>
        /// <param name="trans">写事务的事务控制器.</param>
        /// <param name="func">用于创建删除条件.</param>
        /// <exception cref="ArgumentNullException">当未指派事务控制器时引发此异常.</exception>
        /// <exception cref="Exception">当未指定更新条件或删除过程产生错误时引发此异常.</exception>
        /// <returns></returns>
        public int Delete(DBTransactionController trans, Func <TEntityAgent, object[]> func)
        {
            if (trans == null)
            {
                throw new ArgumentNullException(nameof(trans));
            }
            if (func == null)
            {
                throw new Exception("在不指定条件的情况下将会删除整个数据表中的所有数据,该操作已被禁止.");
            }
            EntityTableAttribute tableAttribute = GetTableAttribute();
            QuickDataChanger     DC             = new QuickDataChanger(trans, Writer);
            TEntityAgent         agent          = new TEntityAgent();

            agent.TableContext = this;
            DC.Conditions.AddRange(func(agent));
            trans.DBA.Errors.Clear();
            int result = DC.Delete(tableAttribute.TableName);

            if (result == -1)
            {
                if (trans.DBA.Errors != null && trans.DBA.Errors.Count > 0)
                {
                    throw new Exception(trans.DBA.Errors[0].Message);
                }
                else
                {
                    throw new Exception("删除数据是产生了未知的错误.");
                }
            }
            return(result);
        }
        /// <summary>
        /// 获取数据表的映射信息.
        /// </summary>
        /// <returns></returns>
        public override EntityTableAttribute GetTableAttribute()
        {
            Type agentType = typeof(TEntityAgent);

            if (TableAttributeCache.ContainsKey(agentType))
            {
                return(TableAttributeCache[agentType]);
            }

            object[] Attributes = agentType.GetCustomAttributes(typeof(EntityTableAttribute), true);
            if (Attributes == null || Attributes.Length < 0)
            {
                throw new NotSupportedException(string.Format("Not supported table context object, please use {1} for class: {0}.", typeof(EntityTableAttribute).FullName, agentType.FullName));
            }
            EntityTableAttribute tableAttribute = (EntityTableAttribute)Attributes[0];

            lock (TableAttributeCache) // 防止多任务时产生并发调用而引起错误
            {
                if (!(TableAttributeCache.ContainsKey(agentType)))
                {
                    TableAttributeCache.Add(agentType, tableAttribute);
                }
            }
            return(tableAttribute);
        }
        /// <summary>
        /// 执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。
        /// </summary>
        /// <param name="action">用于构建查询命令.</param>
        /// <returns></returns>
        public object QueryScalar(Action <TEntityAgent, TableQuerySelector> action)
        {
            EntityTableAttribute entityTable = GetTableAttribute();
            TEntityAgent         agent       = new TEntityAgent();

            agent.TableContext = this;
            TableQuerySelector selector = new TableQuerySelector(entityTable.TableName);

            action(agent, selector);
            object Result;

            if (BatchProccesser == null)
            {
                Result = Reader.ExecuteScalar(selector.DbCommand);
                if (Result == null && Reader.DBA.Error != null)
                {
                    throw new Exception(Reader.DBA.Error.Message);
                }
            }
            else
            {
                Result = BatchProccesser.Commander.QueryScalar(selector.DbCommand);
            }
            return(Result);
        }
        /// <summary>
        /// 删除数据表中满足指定条件的数据.
        /// </summary>
        /// <param name="func">用于创建删除条件.</param>
        /// <exception cref="Exception">当未指定更新条件或删除过程产生错误时引发此异常.</exception>
        /// <returns>返回受影响记录数.</returns>
        public int Delete(Func <TEntityAgent, object[]> func)
        {
            if (func == null)
            {
                throw new Exception("在不指定条件的情况下将会删除整个数据表中的所有数据,该操作已被禁止.");
            }
            EntityTableAttribute tableAttribute = GetTableAttribute();
            TEntityAgent         agent          = new TEntityAgent();

            agent.TableContext = this;
            object[] conditions = func(agent);
            int      result     = 0;

            if (BatchProccesser == null)
            {
                QuickDataChanger DC = new QuickDataChanger(Writer);
                DC.Conditions.AddRange(conditions);
                result = DC.Delete(tableAttribute.TableName);
                if (result == -1)
                {
                    throw new Exception(Writer.DBA.Error.Message);
                }
            }
            else
            {
                DbCommandBuilder cb = new DbCommandBuilder();
                cb.Delete(tableAttribute.TableName).Where(conditions);
                result = BatchProccesser.Commander.ExecuteNonQuery(cb);
            }
            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// 更新数据表中的记录.
        /// </summary>
        /// <typeparam name="TEntity">数据表对应的实体类型.</typeparam>
        /// <param name="entity">实体对象.</param>
        /// <param name="func">用于创建更新条件.</param>
        /// <exception cref="ArgumentNullException">当必备的参数为空时引发此异常.</exception>
        /// <exception cref="Exception">当执行更新时产生错误时引发此异常.</exception>
        /// <returns>返回受影响的记录数.</returns>
        protected int Update <TEntity>(TEntity entity, Func <TEntityAgent, object[]> func) where TEntity : DataEntity, new()
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (func == null)
            {
                throw new Exception("未指定更新条件时,整个数据表中的所有数据都将被更新为一样的,此操作已被禁止.");
            }
            // 过滤掉自增长字段.
            string[]             withOutFields  = GetWithOutFields(entity.GetType());
            EntityTableAttribute tableAttribute = GetTableAttribute();
            QuickDataChanger     DC             = new QuickDataChanger(Writer);

            if (func != null)
            {
                TEntityAgent agent = new TEntityAgent();
                agent.TableContext = this;
                DC.Conditions.AddRange(func(agent));
            }
            int result = DC.SaveToDataBase(tableAttribute.TableName, entity.ToDictionary(withOutFields), true);

            if (result == -1) // 若更新失败时向外界抛出异常.
            {
                throw new Exception(Writer.DBA.Error.Message);
            }
            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// 向多表查询中添加一个联合查询的表.
        /// </summary>
        /// <typeparam name="TEntityAgent">表的实体映射代理对象.</typeparam>
        /// <returns></returns>
        public EntityJoinSelector Join <TEntityAgent>() where TEntityAgent : EntityAgent, new()
        {
            if (sBlock == null)
            {
                throw new NullReferenceException("Please invoke in advance the \"From\" method.");
            }
            TEntityAgent agent   = new TEntityAgent();
            TableMapper  context = agent.CreateContext();

            context.SetDataEngine(ReadEngine, null);
            agent.TableContext     = context;
            agent.IncludeTableName = true;  // 指法查询代理对象在生成字段信息时带上表名.
            // 将实体表的代理类记录下来,后面组织查询时还要用到.
            if (!(AgentsIndexes.ContainsKey(typeof(TEntityAgent))))
            {
                AgentBufferItem BufferItem = new AgentBufferItem(agent);
                AgentsIndexes.Add(typeof(TEntityAgent), BufferItem);
                Agents.Add(BufferItem);
            }
            // 向 FROM 子向中添加 LEFT JOIN 子句.
            EntityTableAttribute tableAttribute = context.GetTableAttribute();
            LeftJoinDescription  leftJoin       = fm.LeftJoin(fm.Table(tableAttribute.TableName));

            fBlock.Content.Add(leftJoin);
            // 返回 JEFT JOIN 子句的筛选器构建对象.
            return(new EntityJoinSelector(this, leftJoin, (t) => {
                if (AgentsIndexes.ContainsKey(t))
                {
                    return AgentsIndexes[t].Agent <EntityAgent>();
                }
                return null;
            }));
        }
Beispiel #7
0
        /// <summary>
        /// 根据指定的条件查询指定实体对应的表,并返回数据集合.
        /// </summary>
        /// <typeparam name="TEntity">对应数据库表的实体类型.</typeparam>
        /// <param name="action">用于指定查询条件.</param>
        /// <returns></returns>
        protected List <TEntity> Select <TEntity>(Action <TEntityAgent, SelectBlock> action) where TEntity : DataEntity, new()
        {
            EntityTableAttribute entityTable = GetTableAttribute();
            DbCommandBuilder     Command     = new DbCommandBuilder();
            SelectBlock          select      = Command.Select(td.Field("*")).From(entityTable.TableName);
            TEntityAgent         agent       = new TEntityAgent();

            agent.TableContext = this;
            action(agent, select);
            return(ExecuteQuery <TEntity>(Command));
        }
Beispiel #8
0
        /// <summary>
        /// 向数据表中添加一条记录.
        /// </summary>
        /// <typeparam name="TEntity">数据表对应的实体类型.</typeparam>
        /// <param name="entity">实体对象.</param>
        /// <param name="trans">写事务的事务控制器.</param>
        /// <exception cref="Exception">当新增数据失败时引发该异常.</exception>
        protected void Add <TEntity>(TEntity entity, DBTransactionController trans = null) where TEntity : DataEntity, new()
        {
            if (entity == null)
            {
                return;
            }
            // 增加记录时过滤掉自增长字段.
            string[] withOutFields = GetWithOutFields(entity.GetType());
            // 向数据库中增加记录
            bool InTransaction = trans != null;
            EntityTableAttribute tableAttribute = GetTableAttribute();
            QuickDataChanger     DC;

            if (InTransaction)
            {
                DC = new QuickDataChanger(trans, Writer);
            }
            else
            {
                DC = new QuickDataChanger(Writer);
            }
            int result = DC.SaveToDataBase(tableAttribute.TableName, entity.ToDictionary(withOutFields), false);

            if (result == -1) // 若添加失败则向外界抛出异常.
            {
                string Error;
                if (InTransaction)
                {
                    Error = (trans.DBA.Errors != null && trans.DBA.Errors.Count > 0) ? trans.DBA.Errors[0].Message : string.Format("新增:{0}是产生未知错误.", entity.GetType().Name);
                }
                else
                {
                    Error = (Writer.DBA.Error == null) ? string.Format("新增:{0}是产生未知错误.", entity.GetType().Name) : Writer.DBA.Error.Message;
                }
                throw new Exception(Error);
            }
            else // 新增成功时更新实体中的自增长字段值.
            {
                if (withOutFields.Length > 0)
                {
                    if (InTransaction)
                    {
                        entity.SetValue(withOutFields[withOutFields.Length - 1], trans.DBA.SCOPE_IDENTITY, true);
                    }
                    else
                    {
                        entity.SetValue(withOutFields[withOutFields.Length - 1], Writer.DBA.SCOPE_IDENTITY, true);
                    }
                }
            }
        }
        /// <summary>
        /// 更新数据表中的记录.
        /// </summary>
        /// <typeparam name="TEntity">数据表对应的实体类型.</typeparam>
        /// <param name="entity">实体对象.</param>
        /// <param name="func">用于创建更新条件.</param>
        /// <exception cref="ArgumentNullException">当必备的参数为空时引发此异常.</exception>
        /// <exception cref="Exception">当执行更新时产生错误时引发此异常.</exception>
        /// <returns>返回受影响的记录数.</returns>
        protected int Update <TEntity>(TEntity entity, Func <TEntityAgent, object[]> func) where TEntity : DataEntity, new()
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (func == null)
            {
                throw new Exception("未指定更新条件时,整个数据表中的所有数据都将被更新为一样的,此操作已被禁止.");
            }
            // 过滤掉自增长字段.
            string[]             withOutFields  = GetWithOutFields(entity.GetType());
            EntityTableAttribute tableAttribute = GetTableAttribute();

            object[] conditions = null;
            if (func != null)  // 获得外部 lambda 表达式返回的条件.
            {
                TEntityAgent agent = new TEntityAgent();
                agent.TableContext = this;
                conditions         = func(agent);
            }
            int result = 0;

            if (BatchProccesser == null)  //非同连接分批处理模式.
            {
                QuickDataChanger DC = new QuickDataChanger(Writer);
                if (conditions != null)
                {
                    DC.Conditions.AddRange(conditions);
                }
                result = DC.SaveToDataBase(tableAttribute.TableName, entity.ToDictionary(withOutFields), true);
                if (result == -1) // 若更新失败时向外界抛出异常.
                {
                    throw new Exception(Writer.DBA.Error.Message);
                }
            }
            else  //在同一个连接的分批处理模式.
            {
                List <IDescription>         exp  = new List <IDescription>();
                Dictionary <string, object> data = entity.ToDictionary(withOutFields);
                foreach (KeyValuePair <string, object> item in data)
                {
                    exp.Add(td.Field(item.Key) == item.Value);
                }
                DbCommandBuilder cb = new DbCommandBuilder();
                cb.Update(tableAttribute.TableName).Set(exp.ToArray()).Where(conditions);
                result = BatchProccesser.Commander.ExecuteNonQuery(cb);
            }
            return(result);
        }
 /// <summary>
 /// 获取或设置表名称.
 /// </summary>
 /// <returns></returns>
 internal override string GetTableName()
 {
     if (string.IsNullOrEmpty(tableName))
     {
         EntityTableAttribute tableAttribute = GetTableAttribute();
         StringBuilder        tabName        = new StringBuilder();
         tabName.Append(Reader.CommandParserAdapter.ElemIdentifierL);
         tabName.Append(tableAttribute.TableName);
         tabName.Append(Reader.CommandParserAdapter.ElemIdentifierR);
         tableName = tabName.ToString();
         return(tabName.ToString());
     }
     else
     {
         return(tableName);
     }
 }
Beispiel #11
0
        /// <summary>
        /// 在事务中更新数据表中的记录.
        /// </summary>
        /// <typeparam name="TEntity">数据表对应的实体类型.</typeparam>
        /// <param name="trans">写事务的事务控制器.</param>
        /// <param name="entity">实体对象.</param>
        /// <param name="func">用于创建更新条件.</param>
        /// <exception cref="ArgumentNullException">当必备的参数为空时引发此异常.</exception>
        /// <exception cref="Exception">当执行更新时产生错误时引发此异常.</exception>
        /// <returns>返回受影响的记录数.</returns>
        protected int Update <TEntity>(DBTransactionController trans, TEntity entity, Func <TEntityAgent, object[]> func) where TEntity : DataEntity, new()
        {
            if (trans == null)
            {
                throw new ArgumentNullException(nameof(trans));
            }
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            if (func == null)
            {
                throw new Exception("未指定更新条件时,整个数据表中的所有数据都将被更新为一样的,此操作已被禁止.");
            }
            // 过滤掉自增长字段.
            // 过滤掉自增长字段.
            string[]             withOutFields  = GetWithOutFields(entity.GetType());
            EntityTableAttribute tableAttribute = GetTableAttribute();
            QuickDataChanger     DC             = new QuickDataChanger(trans, Writer);

            if (func != null)
            {
                TEntityAgent agent = new TEntityAgent();
                agent.TableContext = this;
                DC.Conditions.AddRange(func(agent));
            }
            trans.DBA.Errors.Clear();
            int result = DC.SaveToDataBase(tableAttribute.TableName, entity.ToDictionary(withOutFields), true);

            if (result == -1) // 若更新失败时向外界抛出异常.
            {
                string Error;
                if (trans.DBA.Errors.Count < 1)
                {
                    Error = "更新表时产生了未知的异常.";
                }
                else
                {
                    Error = trans.DBA.Errors[0].Message;
                }
                throw new Exception(Error);
            }
            return(result);
        }
        /// <summary>
        /// 查询指定实体对应的表,并返回数据集合.
        /// </summary>
        /// <typeparam name="TEntity">对应数据库表的实体类型.</typeparam>
        /// <param name="selector">返回查询条件的方法.</param>
        /// <exception cref="NotSupportedException">当<c>TEntity</c>指定的实体类型未标记<see cref="EntityTableAttribute"/>属性时引发该异常</exception>
        /// <exception cref="Exception">当数据库查询过程产生错误时引发该异常.</exception>
        /// <returns></returns>
        protected List <TEntity> Select <TEntity>(Func <TEntityAgent, object> selector) where TEntity : DataEntity, new()
        {
            EntityTableAttribute entityTable = GetTableAttribute();
            DbCommandBuilder     Command     = new DbCommandBuilder();
            TEntityAgent         agent       = new TEntityAgent();

            agent.TableContext = this;
            object Conditions = selector(agent);

            if (Conditions == null)
            {
                Command.Select(agent.GetFieldsArray()).From(entityTable.TableName);
            }
            else
            {
                Command.Select(agent.GetFieldsArray()).From(entityTable.TableName).Where(Conditions);
            }
            return(ExecuteQuery <TEntity>(Command));
        }
Beispiel #13
0
        /// <summary>
        /// 删除数据表中满足指定条件的数据.
        /// </summary>
        /// <param name="func">用于创建删除条件.</param>
        /// <exception cref="Exception">当未指定更新条件或删除过程产生错误时引发此异常.</exception>
        /// <returns>返回受影响记录数.</returns>
        public int Delete(Func <TEntityAgent, object[]> func)
        {
            if (func == null)
            {
                throw new Exception("在不指定条件的情况下将会删除整个数据表中的所有数据,该操作已被禁止.");
            }
            EntityTableAttribute tableAttribute = GetTableAttribute();
            QuickDataChanger     DC             = new QuickDataChanger(Writer);
            TEntityAgent         agent          = new TEntityAgent();

            agent.TableContext = this;
            DC.Conditions.AddRange(func(agent));
            int result = DC.Delete(tableAttribute.TableName);

            if (result == -1)
            {
                throw new Exception(Writer.DBA.Error.Message);
            }
            return(result);
        }
Beispiel #14
0
        /// <summary>
        /// 开始建立查询命令对象树.
        /// </summary>
        /// <typeparam name="TEntityAgent">表对应的实体映射代理对象.</typeparam>
        /// <returns></returns>
        internal MultiQuerySelector From <TEntityAgent>() where TEntityAgent : EntityAgent, new()
        {
            sBlock = Command.Select();
            TEntityAgent agent   = new TEntityAgent();
            TableMapper  context = agent.CreateContext();

            context.SetDataEngine(ReadEngine, null);
            agent.TableContext     = context;
            agent.IncludeTableName = true; // 指法查询代理对象在生成字段信息时带上表名.
            // 将实体表的代理类记录下来,后面组织查询时还要用到.
            if (!(AgentsIndexes.ContainsKey(typeof(TEntityAgent))))
            {
                AgentBufferItem BufferItem = new AgentBufferItem(agent);
                AgentsIndexes.Add(typeof(TEntityAgent), BufferItem);
                Agents.Add(BufferItem);
            }
            // 向 FROM 了向中添加查询的表.
            EntityTableAttribute tableAttribute = context.GetTableAttribute();

            fBlock.Content.Add(fm.Table(tableAttribute.TableName));
            sBlock.Blocks.Add(fBlock);
            return(this);
        }
        /// <summary>
        /// 向数据表中添加一条记录.
        /// </summary>
        /// <typeparam name="TEntity">数据表对应的实体类型.</typeparam>
        /// <param name="entity">实体对象.</param>
        /// <param name="trans">写事务的事务控制器.</param>
        /// <exception cref="Exception">当新增数据失败时引发该异常.</exception>
        protected void Add <TEntity>(TEntity entity, DBTransactionController trans = null) where TEntity : DataEntity, new()
        {
            if (entity == null)
            {
                return;
            }
            // 增加记录时过滤掉自增长字段.
            string[]             withOutFields  = GetWithOutFields(entity.GetType());
            EntityTableAttribute tableAttribute = GetTableAttribute();
            int result = 0;

            if (BatchProccesser == null) // 非同连接分批处理模式.
            {
                bool             InTransaction = trans != null;
                QuickDataChanger DC;
                if (InTransaction)
                {
                    DC = new QuickDataChanger(trans, Writer);
                }
                else
                {
                    DC = new QuickDataChanger(Writer);
                }
                result = DC.SaveToDataBase(tableAttribute.TableName, entity.ToDictionary(withOutFields), false);
                if (result == -1) // 若添加失败则向外界抛出异常.
                {
                    string Error;
                    if (InTransaction)
                    {
                        Error = (trans.DBA.Errors != null && trans.DBA.Errors.Count > 0) ? trans.DBA.Errors[0].Message : string.Format("新增:{0}是产生未知错误.", entity.GetType().Name);
                    }
                    else
                    {
                        Error = (Writer.DBA.Error == null) ? string.Format("新增:{0}是产生未知错误.", entity.GetType().Name) : Writer.DBA.Error.Message;
                    }
                    throw new Exception(Error);
                }
                else // 新增成功时更新实体中的自增长字段值.
                {
                    if (withOutFields.Length > 0)
                    {
                        if (InTransaction)
                        {
                            entity.SetValue(withOutFields[withOutFields.Length - 1], trans.DBA.SCOPE_IDENTITY, true);
                        }
                        else
                        {
                            entity.SetValue(withOutFields[withOutFields.Length - 1], Writer.DBA.SCOPE_IDENTITY, true);
                        }
                    }
                }
            }
            else // 在同一个连接的分批处理模式.
            {
                List <FieldDescription>     fields = new List <FieldDescription>();
                List <object>               values = new List <object>();
                Dictionary <string, object> data   = entity.ToDictionary(withOutFields);
                foreach (KeyValuePair <string, object> item in data)
                {
                    fields.Add(td.Field(item.Key));
                    values.Add(item.Value);
                }
                DbCommandBuilder cb = new DbCommandBuilder();
                cb.Insert(tableAttribute.TableName, fields.ToArray()).Values(values.ToArray());
                result = BatchProccesser.Commander.ExecuteNonQuery(cb);
                if (withOutFields.Length > 0 && result > 0)
                {
                    entity.SetValue(withOutFields[withOutFields.Length - 1], BatchProccesser.Commander.SCOPE_IDENTITY, true);
                }
            }
        }