Exemple #1
0
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="body">a => new User() { Name = a.Name, Age = a.Age + 100, Gender = Gender.Man, OpTime = DateTime.Now }</param>
        /// <param name="condition">a => a.Id == 1</param>
        /// <returns></returns>
        public int Edit(Expression <Func <TEntity, TEntity> > body, Expression <Func <TEntity, bool> > condition)
        {
            Checks.NotNull(body, "body");

            TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(typeof(TEntity));

            Dictionary <MemberInfo, Expression> updateColumns = InitMemberExtractor.Extract(body);

            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(null);
            DbExpression            conditionExp     = expressionParser.ParseFilterPredicate(condition);
            DbUpdateExpression      e = new DbUpdateExpression(typeDescriptor.Table, conditionExp);

            foreach (var kv in updateColumns)
            {
                MemberInfo key = kv.Key;
                MappingMemberDescriptor memberDescriptor = typeDescriptor.TryGetMappingMemberDescriptor(key);

                e.UpdateColumns.Add(memberDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            IDbExpressionTranslator translator = this.DbContext.DatabaseProvider.CreateDbExpressionTranslator();
            List <DbParam>          parameters;
            string sql = translator.Translate(e, out parameters);

            return(this.DbContext.ExecuteNoQuery(sql, parameters.ToArray()));
        }
Exemple #2
0
        public DefaultDialect()
        {
            Parser = new DefaultExpressionParser();

            ParameterEvaluators = new List <IParameterEvaluatorFactory> {
                new PatternLookupEvaluatorFactory(),
                new ReflectionParameterEvaluatorFactory(),
                new SimpleParameterEvaluatorFactory()
            };

            ValueFormatters = new List <IValueFormatterFactory> {
                new StringCaseFormatterFactory(),
                new RomanNumberFormatterFactory(),
                new StringFormatFormatterFactory(),
                new DefaultFormatterFactory()
            };

            SwitchConditionEvaluators = new List <ISwitchConditionEvaluatorFactory> {
                new TakeAllConditionFactory(),
                new BooleanExpressionConditionFactory(),
                new LookupConditionFactory(),
                new ArithmeticConditionFactory(),
                new IntervalConditionFactory(),
                new ValueListConditionFactory()
            };

            FormatGroupExpander = new HashTagFormatGroupExpander();
        }
Exemple #3
0
        public virtual int Update <TEntity>(Expression <Func <TEntity, bool> > condition, Expression <Func <TEntity, TEntity> > content, string table, int limits)
        {
            Utils.CheckNull(condition);
            Utils.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            Dictionary <MemberInfo, Expression> updateColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);

            DbExpression conditionExp = expressionParser.ParseFilterPredicate(condition);

            MySqlDbUpdateExpression e = new MySqlDbUpdateExpression(explicitDbTable ?? typeDescriptor.Table, conditionExp);

            foreach (var kv in updateColumns)
            {
                MemberInfo         key = kv.Key;
                PropertyDescriptor propertyDescriptor = typeDescriptor.TryGetPropertyDescriptor(key);

                if (propertyDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (propertyDescriptor.IsPrimaryKey)
                {
                    throw new ChloeException(string.Format("Could not update the primary key '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("Could not update the identity column '{0}'.", propertyDescriptor.Column.Name));
                }

                e.UpdateColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            e.Limits = limits;

            if (e.UpdateColumns.Count == 0)
            {
                return(0);
            }

            return(this.ExecuteSqlCommand(e));
        }
Exemple #4
0
        public override int Update <TEntity>(Expression <Func <TEntity, bool> > condition, Expression <Func <TEntity, TEntity> > content, string table)
        {
            Utils.CheckNull(condition);
            Utils.CheckNull(content);

            TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(typeof(TEntity));

            Dictionary <MemberInfo, Expression> updateColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);

            DbExpression conditionExp = expressionParser.ParseFilterPredicate(condition);

            DbUpdateExpression e = new DbUpdateExpression(explicitDbTable ?? typeDescriptor.Table, conditionExp);

            foreach (var kv in updateColumns)
            {
                MemberInfo key = kv.Key;
                MappingMemberDescriptor memberDescriptor = typeDescriptor.TryGetMappingMemberDescriptor(key);

                if (memberDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (memberDescriptor.IsPrimaryKey)
                {
                    throw new ChloeException(string.Format("Could not update the primary key '{0}'.", memberDescriptor.Column.Name));
                }

                SequenceAttribute attr = (SequenceAttribute)memberDescriptor.GetCustomAttribute(typeof(SequenceAttribute));
                if (attr != null)
                {
                    throw new ChloeException(string.Format("Could not update the column '{0}',because it's mapping member has define a sequence.", memberDescriptor.Column.Name));
                }

                e.UpdateColumns.Add(memberDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            if (e.UpdateColumns.Count == 0)
            {
                return(0);
            }

            return(this.ExecuteSqlCommand(e));
        }
Exemple #5
0
        protected virtual async Task <int> Delete <TEntity>(Expression <Func <TEntity, bool> > condition, string table, bool @async)
        {
            PublicHelper.CheckNull(condition);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            DbTable dbTable = typeDescriptor.GenDbTable(table);
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(dbTable);
            DbExpression            conditionExp     = expressionParser.ParseFilterPredicate(condition);

            DbDeleteExpression e = new DbDeleteExpression(dbTable, conditionExp);

            return(await this.ExecuteNonQuery(e, @async));
        }
Exemple #6
0
 public DefaultExpressionParser GetExpressionParser(DbTable explicitDbTable)
 {
     if (explicitDbTable == null)
     {
         if (this._expressionParser == null)
         {
             this._expressionParser = new DefaultExpressionParser(this, null);
         }
         return(this._expressionParser);
     }
     else
     {
         return(new DefaultExpressionParser(this, explicitDbTable));
     }
 }
Exemple #7
0
        public DefaultExpressionParser GetExpressionParser(DbTable explicitDbTable)
        {
            DbTable dbTable = explicitDbTable ?? this.Table;

            if (dbTable == this.Table)
            {
                if (this._expressionParser == null)
                {
                    this._expressionParser = new DefaultExpressionParser(this, null);
                }

                return(this._expressionParser);
            }

            return(new DefaultExpressionParser(this, dbTable));
        }
Exemple #8
0
        /// <summary>
        /// 条件删除
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public int Remove(Expression <Func <TEntity, bool> > condition)
        {
            Checks.NotNull(condition, "condition");

            TypeDescriptor          typeDescriptor   = TypeDescriptor.GetDescriptor(typeof(TEntity));
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(null);
            DbExpression            conditionExp     = expressionParser.ParseFilterPredicate(condition);

            DbDeleteExpression e = new DbDeleteExpression(typeDescriptor.Table, conditionExp);

            IDbExpressionTranslator translator = this.DbContext.DatabaseProvider.CreateDbExpressionTranslator();
            List <DbParam>          parameters;
            string sql = translator.Translate(e, out parameters);

            return(this.DbContext.ExecuteNoQuery(sql, parameters.ToArray()));
        }
Exemple #9
0
        public virtual int Delete <TEntity>(Expression <Func <TEntity, bool> > condition, string table, int limits)
        {
            PublicHelper.CheckNull(condition);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(dbTable);
            DbExpression            conditionExp     = expressionParser.ParseFilterPredicate(condition);

            MySqlDbDeleteExpression e = new MySqlDbDeleteExpression(dbTable, conditionExp);

            e.Limits = limits;

            return(this.ExecuteNonQuery(e));
        }
Exemple #10
0
        protected virtual async Task <int> Update <TEntity>(Expression <Func <TEntity, bool> > condition, Expression <Func <TEntity, TEntity> > content, string table, bool @async)
        {
            PublicHelper.CheckNull(condition);
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            Dictionary <MemberInfo, Expression> updateColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);

            DbExpression conditionExp = expressionParser.ParseFilterPredicate(condition);

            DbUpdateExpression e = new DbUpdateExpression(explicitDbTable ?? typeDescriptor.Table, conditionExp);

            foreach (var kv in updateColumns)
            {
                MemberInfo key = kv.Key;
                PrimitivePropertyDescriptor propertyDescriptor = typeDescriptor.GetPrimitivePropertyDescriptor(key);

                if (propertyDescriptor.IsPrimaryKey)
                {
                    throw new ChloeException(string.Format("Could not update the primary key '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsAutoIncrement || propertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("Could not update the column '{0}', because it's mapping member is auto increment or has define a sequence.", propertyDescriptor.Column.Name));
                }

                e.UpdateColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            if (e.UpdateColumns.Count == 0)
            {
                return(0);
            }

            return(await this.ExecuteNonQuery(e, @async));
        }
Exemple #11
0
        public virtual int Update <TEntity>(Expression <Func <TEntity, bool> > condition, Expression <Func <TEntity, TEntity> > content, string table, int limits)
        {
            PublicHelper.CheckNull(condition);
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            Dictionary <MemberInfo, Expression> updateColumns = InitMemberExtractor.Extract(content);

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(dbTable);

            DbExpression conditionExp = expressionParser.ParseFilterPredicate(condition);

            MySqlDbUpdateExpression e = new MySqlDbUpdateExpression(dbTable, conditionExp);

            foreach (var kv in updateColumns)
            {
                MemberInfo key = kv.Key;
                PrimitivePropertyDescriptor propertyDescriptor = typeDescriptor.GetPrimitivePropertyDescriptor(key);

                if (propertyDescriptor.IsPrimaryKey)
                {
                    throw new ChloeException(string.Format("Could not update the primary key '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("Could not update the identity column '{0}'.", propertyDescriptor.Column.Name));
                }

                e.UpdateColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            e.Limits = limits;

            if (e.UpdateColumns.Count == 0)
            {
                return(0);
            }

            return(this.ExecuteNonQuery(e));
        }
Exemple #12
0
        public virtual int Delete <TEntity>(Expression <Func <TEntity, bool> > condition, string table)
        {
            Utils.CheckNull(condition);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbExpression            conditionExp     = expressionParser.ParseFilterPredicate(condition);

            DbDeleteExpression e = new DbDeleteExpression(explicitDbTable ?? typeDescriptor.Table, conditionExp);

            return(this.ExecuteNonQuery(e));
        }
Exemple #13
0
        public override object Insert <TEntity>(Expression <Func <TEntity> > content, string table)
        {
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            if (typeDescriptor.PrimaryKeys.Count > 1)
            {
                /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */
                throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName));
            }

            PropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault();

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbInsertExpression      insertExp        = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo         key = kv.Key;
                PropertyDescriptor propertyDescriptor = typeDescriptor.TryGetPropertyDescriptor(key);

                if (propertyDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (propertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name));
                    }
                    else
                    {
                        keyVal = val;
                        insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType));
                        continue;
                    }
                }

                insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            foreach (var item in typeDescriptor.PropertyDescriptors.Where(a => a.HasSequence()))
            {
                DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(item);
                insertExp.InsertColumns.Add(item.Column, getNextValueForSequenceExp);
            }

            if (keyPropertyDescriptor != null)
            {
                //主键为空并且主键又不是自增列
                if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name));
                }
            }

            if (keyPropertyDescriptor == null)
            {
                this.ExecuteSqlCommand(insertExp);
                return(keyVal); /* It will return null if an entity does not define primary key. */
            }
            if (!keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence())
            {
                this.ExecuteSqlCommand(insertExp);
                return(keyVal);
            }

            IDbExpressionTranslator translator = this.DatabaseProvider.CreateDbExpressionTranslator();
            List <DbParam>          parameters;
            string sql = translator.Translate(insertExp, out parameters);

            if (keyPropertyDescriptor.IsAutoIncrement)
            {
                /* 自增 id 不能用 output  inserted.Id 输出,因为如果表设置了触发器的话会报错 */
                sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause());
            }
            else if (keyPropertyDescriptor.HasSequence())
            {
                insertExp.Returns.Add(keyPropertyDescriptor.Column);
            }

            object ret = this.Session.ExecuteScalar(sql, parameters.ToArray());

            if (ret == null || ret == DBNull.Value)
            {
                throw new ChloeException("Unable to get the identity/sequence value.");
            }

            ret = PublicHelper.ConvertObjType(ret, typeDescriptor.AutoIncrement.PropertyType);
            return(ret);
        }
Exemple #14
0
        protected virtual async Task <object> Insert <TEntity>(Expression <Func <TEntity> > content, string table, bool @async)
        {
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            if (typeDescriptor.PrimaryKeys.Count > 1)
            {
                /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */
                throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName));
            }

            PrimitivePropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault();

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbInsertExpression      e = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo key = kv.Key;
                PrimitivePropertyDescriptor propertyDescriptor = typeDescriptor.GetPrimitivePropertyDescriptor(key);

                if (propertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name));
                    }
                    else
                    {
                        keyVal = val;
                        e.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType));
                        continue;
                    }
                }

                e.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            if (keyPropertyDescriptor != null)
            {
                //主键为空并且主键又不是自增列
                if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name));
                }
            }

            if (keyPropertyDescriptor == null || !keyPropertyDescriptor.IsAutoIncrement)
            {
                await this.ExecuteNonQuery(e, @async);

                return(keyVal); /* It will return null if an entity does not define primary key. */
            }

            IDbExpressionTranslator translator    = this.DatabaseProvider.CreateDbExpressionTranslator();
            DbCommandInfo           dbCommandInfo = translator.Translate(e);

            dbCommandInfo.CommandText = string.Concat(dbCommandInfo.CommandText, ";", this.GetSelectLastInsertIdClause());

            //SELECT @@IDENTITY 返回的是 decimal 类型
            object retIdentity = await this.ExecuteScalar(dbCommandInfo, @async);

            if (retIdentity == null || retIdentity == DBNull.Value)
            {
                throw new ChloeException("Unable to get the identity value.");
            }

            retIdentity = PublicHelper.ConvertObjectType(retIdentity, typeDescriptor.AutoIncrement.PropertyType);
            return(retIdentity);
        }
Exemple #15
0
        public override object Insert <TEntity>(Expression <Func <TEntity> > content, string table)
        {
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            if (typeDescriptor.PrimaryKeys.Count > 1)
            {
                /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */
                throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName));
            }

            PropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault();

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbInsertExpression      insertExp        = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo         key = kv.Key;
                PropertyDescriptor propertyDescriptor = typeDescriptor.TryGetPropertyDescriptor(key);

                if (propertyDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (propertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("Could not insert value into the auto increment column '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name));
                    }
                    else
                    {
                        keyVal = val;
                        insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType));
                        continue;
                    }
                }

                insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            foreach (PropertyDescriptor propertyDescriptor in typeDescriptor.PropertyDescriptors)
            {
                if (propertyDescriptor.IsAutoIncrement && propertyDescriptor.IsPrimaryKey)
                {
                    insertExp.Returns.Add(propertyDescriptor.Column);
                    continue;
                }

                if (propertyDescriptor.HasSequence())
                {
                    DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(propertyDescriptor);
                    insertExp.InsertColumns.Add(propertyDescriptor.Column, getNextValueForSequenceExp);

                    if (propertyDescriptor.IsPrimaryKey)
                    {
                        insertExp.Returns.Add(propertyDescriptor.Column);
                    }

                    continue;
                }
            }

            if (keyPropertyDescriptor != null)
            {
                //主键为空并且主键又不是自增列
                if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name));
                }
            }

            List <DbParam> parameters;

            this.ExecuteNonQuery(insertExp, out parameters);

            if (keyPropertyDescriptor != null && (keyPropertyDescriptor.IsAutoIncrement || keyPropertyDescriptor.HasSequence()))
            {
                string  outputColumnName = Utils.GenOutputColumnParameterName(keyPropertyDescriptor.Column.Name);
                DbParam outputParam      = parameters.Where(a => a.Direction == ParamDirection.Output && a.Name == outputColumnName).First();
                keyVal = PublicHelper.ConvertObjType(outputParam.Value, keyPropertyDescriptor.PropertyType);
            }

            return(keyVal); /* It will return null if an entity does not define primary key. */
        }
Exemple #16
0
        public override object Insert <TEntity>(Expression <Func <TEntity> > content, string table)
        {
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            if (typeDescriptor.PrimaryKeys.Count > 1)
            {
                /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */
                throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName));
            }

            PropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault();

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbInsertExpression      insertExp        = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo         key = kv.Key;
                PropertyDescriptor propertyDescriptor = typeDescriptor.TryGetPropertyDescriptor(key);

                if (propertyDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (propertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name));
                    }
                    else
                    {
                        keyVal = val;
                        insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal, propertyDescriptor.PropertyType, propertyDescriptor.Column.DbType));
                        continue;
                    }
                }

                insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            Dictionary <PropertyDescriptor, object> sequenceValues = this.GetSequenceValues(typeDescriptor.PropertyDescriptors.Where(a => a.HasSequence()).ToList());

            foreach (var kv in sequenceValues)
            {
                insertExp.InsertColumns.Add(kv.Key.Column, DbExpression.Parameter(kv.Value));
                if (kv.Key.IsPrimaryKey)
                {
                    keyVal = kv.Value;
                }
            }

            if (keyPropertyDescriptor != null && keyVal == null)
            {
                throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name));
            }

            this.ExecuteSqlCommand(insertExp);
            return(keyVal); /* It will return null if an entity does not define primary key. */
        }
Exemple #17
0
        public override object Insert <TEntity>(Expression <Func <TEntity> > content, string table)
        {
            Utils.CheckNull(content);

            TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(typeof(TEntity));

            MappingMemberDescriptor keyMemberDescriptor = typeDescriptor.PrimaryKey;

            string sequenceName;
            object sequenceValue = null;
            MappingMemberDescriptor defineSequenceMemberDescriptor = GetDefineSequenceMemberDescriptor(typeDescriptor, out sequenceName);

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbInsertExpression      e = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo key = kv.Key;
                MappingMemberDescriptor memberDescriptor = typeDescriptor.TryGetMappingMemberDescriptor(key);

                if (memberDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (memberDescriptor == defineSequenceMemberDescriptor)
                {
                    throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", memberDescriptor.Column.Name));
                }

                if (memberDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", memberDescriptor.MemberInfo.Name));
                    }
                    else
                    {
                        keyVal = val;
                        e.InsertColumns.Add(memberDescriptor.Column, DbExpression.Parameter(keyVal));
                        continue;
                    }
                }

                e.InsertColumns.Add(memberDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            if (keyMemberDescriptor == defineSequenceMemberDescriptor)
            {
                sequenceValue = ConvertIdentityType(this.GetSequenceNextValue(sequenceName), defineSequenceMemberDescriptor.MemberInfoType);

                keyVal = sequenceValue;
                e.InsertColumns.Add(keyMemberDescriptor.Column, DbExpression.Parameter(keyVal));
            }

            if (keyMemberDescriptor != null && keyVal == null)
            {
                throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyMemberDescriptor.MemberInfo.Name));
            }

            this.ExecuteSqlCommand(e);
            return(keyVal); /* It will return null if an entity does not define primary key. */
        }
Exemple #18
0
        public virtual object Insert <TEntity>(Expression <Func <TEntity> > content, string table)
        {
            Utils.CheckNull(content);

            TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(typeof(TEntity));

            MappingMemberDescriptor keyMemberDescriptor           = typeDescriptor.PrimaryKey;
            MappingMemberDescriptor autoIncrementMemberDescriptor = typeDescriptor.AutoIncrement;

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable explicitDbTable = null;

            if (table != null)
            {
                explicitDbTable = new DbTable(table, typeDescriptor.Table.Schema);
            }
            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(explicitDbTable);
            DbInsertExpression      e = new DbInsertExpression(explicitDbTable ?? typeDescriptor.Table);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo key = kv.Key;
                MappingMemberDescriptor memberDescriptor = typeDescriptor.TryGetMappingMemberDescriptor(key);

                if (memberDescriptor == null)
                {
                    throw new ChloeException(string.Format("The member '{0}' does not map any column.", key.Name));
                }

                if (memberDescriptor == autoIncrementMemberDescriptor)
                {
                    throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", memberDescriptor.Column.Name));
                }

                if (memberDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", memberDescriptor.MemberInfo.Name));
                    }
                    else
                    {
                        keyVal = val;
                        e.InsertColumns.Add(memberDescriptor.Column, DbExpression.Parameter(keyVal));
                        continue;
                    }
                }

                e.InsertColumns.Add(memberDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            if (keyMemberDescriptor != null)
            {
                //主键为空并且主键又不是自增列
                if (keyVal == null && keyMemberDescriptor != autoIncrementMemberDescriptor)
                {
                    throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyMemberDescriptor.MemberInfo.Name));
                }
            }

            if (keyMemberDescriptor == null || keyMemberDescriptor != autoIncrementMemberDescriptor)
            {
                this.ExecuteSqlCommand(e);
                return(keyVal); /* It will return null if an entity does not define primary key. */
            }

            IDbExpressionTranslator translator = this.DbContextServiceProvider.CreateDbExpressionTranslator();
            List <DbParam>          parameters;
            string sql = translator.Translate(e, out parameters);

            sql = string.Concat(sql, ";", this.GetSelectLastInsertIdClause());

            //SELECT @@IDENTITY 返回的是 decimal 类型
            object retIdentity = this.Session.ExecuteScalar(sql, parameters.ToArray());

            if (retIdentity == null || retIdentity == DBNull.Value)
            {
                throw new ChloeException("Unable to get the identity value.");
            }

            retIdentity = ConvertIdentityType(retIdentity, autoIncrementMemberDescriptor.MemberInfoType);
            return(retIdentity);
        }
Exemple #19
0
        static void Main(string[] args)
        {
            //TestSwitchCaseCondition("@Test", 1);


            TestSwitchCaseCondition("% 10 = 2 or (1 and < 1)", 1);
            TestSwitchCaseCondition("% 10 = 2 or (1 and < 1)", 12);
            TestSwitchCaseCondition("% 10 = 2 or 5, 6, 7, 8, 9", 7);
            TestSwitchCaseCondition("% 10 = 2 or 5, 6, 7, 8, 9", 15);


            TestSwitchCaseCondition(" +1 % 10 = 1", 10);

            TestSwitchCaseCondition(" + 1 % 10 = 1", 10);

            TestSwitchCaseCondition("%10=1", 1);
            TestSwitchCaseCondition("%10=1", 10);
            TestSwitchCaseCondition("%10=1", 25);
            TestSwitchCaseCondition("%10=1", 11);



            var dialect = new DefaultDialect();
            var manager = new DummyManager();


            var test = "Hej {P1: Format spec} <F1:   {Moo:tahr}> {Abe:kat} #Fisso{1:  Foo 10 #Nested{Boo:Hawrh!} | 10} #Moo{{ab}} #Foo{|?Gok}";

            var p = new DefaultExpressionParser();
            var e = p.Parse(test, null);

            e.Accept(new Printer());

            var eval = new PatternEvaluator(e);

            Console.Out.WriteLine();
            Console.Out.WriteLine(e.ToString());

            Console.Out.WriteLine("Custom expression part");
            var customTest = "Hej {Name}";

            e = p.Parse(customTest, null);
            e.Parts.Add(new TestPart());
            e.Accept(new PatternDecorator(manager, dialect));

            eval = new PatternEvaluator(e);


            e.Accept(new Printer());
            Console.Out.WriteLine();
            Console.Out.WriteLine(eval.Evaluate(
                                      CreateContext(null, manager.CurrentLanguage, new Dictionary <string, object> {
                { "Name", "John" }
            })));
            Console.Out.WriteLine();
            Console.Out.WriteLine(e.ToString());

            var ptest = @"The values are {Name} and <Bold: <Bold:{Test}> <Bold:{Test}>><Bold: {Number:N2} (roman: {Number:roman})>. #Number{1: Singularis: 1 ({#}) | Pluralis\: n ({#})}.
            
                Boolean Expression: #Number{2 or 5: Yes | No}

                ModuloTest: #Number{% 2 = 0: Yes | No}
            
                {Name} has {Name.Length:N2} characters

                Let's enumerate 
                Enum test 1: #EnumTest1{0:{#}|, {#}|-1:"" and {#}""}
                Enum test 2: #EnumTest2{0:{#}|, {#}|-1:"" and {#}""}";

            Console.Out.WriteLine();

            var evaluator = dialect.GetEvaluator(ptest, manager);

            Console.Out.WriteLine(evaluator.Evaluate(
                                      CreateContext(null, manager.CurrentLanguage, new Dictionary <string, object> {
                { "Name", "John Doe" },
                { "Number", 5 },
                { "Bold", "<b>{#}</b>" },
                { "EnumTest1", new string[] { "A", "B", "C", "D" } },
                { "EnumTest2", new string[] { "A" } },
                { "EnumTest3", new string[] { "A", "B" } },
                { "Test", true }
            })));


            var texts = new List <LocalizedText>
            {
                new LocalizedText {
                    Key = "LookupCondition", Pattern = "% 10 <= 2", Language = "en-US", PatternDialect = "Text"
                },

                new LocalizedText {
                    Key = "Plural1", Pattern = "1", Language = "en-US", PatternDialect = "Text"
                },
                new LocalizedText {
                    Key = "Plural2", Pattern = "<20", Language = "en-US", PatternDialect = "Text"
                },

                new LocalizedText {
                    Key = "ShortPlural", Pattern = "The number is #Plural(Number){Not plural|Plural|More plural}", Language = "en-US"
                },

                new LocalizedText {
                    Key = "PluralFun", Pattern = "The number is #Number{@LookupCondition: Plural|Not plural}", Language = "en-US"
                },

                new LocalizedText {
                    Key = "Arithmetic", Pattern = "Test #Number{% 10 = 1: Module | + 1 * 2 > 10: Combined}", Language = "en-US"
                },

                new LocalizedText {
                    Key = "Text one", Pattern = "Test one", Language = "en-US"
                },
                new LocalizedText {
                    Key = "Text two", Pattern = "Hello {UserName}", Language = "en-US"
                },
                new LocalizedText {
                    Key = "Text two", Pattern = "Hej {UserName}", Language = "da-DK"
                },
                new LocalizedText {
                    Key = "Enum", Pattern = @"#0{0: {#Index:roman}: {#}|, {#Index:roman}\: {#}|-1: "" {1} {#Index:roman}\: {#}""}", Language = "en-US"
                },

                new LocalizedText {
                    Key = "Reffed", Pattern = "Test {0} String literal {1}", Language = "en-US"
                },
                new LocalizedText {
                    Key = "Ref test 1", Pattern = "Ref 1: {@Reffed} and Another namespace {@Another__Reffed}", Language = "en-US"
                },
                new LocalizedText {
                    Key = "Ref test 2", Pattern = @"Ref 2: {@Reffed(UserName, ""Moo"")}", Language = "en-US"
                },
                //This one makes sense, and shows why pattern references are neat
                new LocalizedText {
                    Key = "Ref test 3", Pattern = @"You have selected {@Enum(List, 'and')}", Language = "en-US"
                },

                new LocalizedText {
                    Key = "Ref test 3", Namespace = "Another", Pattern = "Test one {@Reffed} and {@__Reffed}", Language = "en-US"
                },

                new LocalizedText {
                    Key = "Reffed", Namespace = "Another", Pattern = "I'm another", Language = "en-US"
                },

                new LocalizedText {
                    Key = "FormattedSwitch", Pattern = "Two decimals #Count:N2{1: One - ({#}) | More - {#}}", Language = "en-US"
                },
            };

            var xml = new XmlTextSource();

            xml.Put(texts.Select(x => new LocalizedTextState {
                Text = x, Status = LocalizedTextStatus.Unchanged
            }), TextMergeOptions.KeepUnused);

            xml.Document.Save("Texts.xml");


            xml          = new XmlTextSource();
            xml.Document = XDocument.Load("Texts.xml");


            manager.Texts.Sources.Add(new PrioritizedTextSource(xml));


            Console.Out.WriteLine(manager.Get("LookupCondition"));
            Console.Out.WriteLine(manager.Get("PluralFun", new { Number = 1 }));

            Console.Out.WriteLine("Shorthand:");
            Console.Out.WriteLine(manager.Get("ShortPlural", new { Number = 30 }));

            Console.Out.WriteLine(manager.Get("Text two", new { UserName = "******" }));

            Console.Out.WriteLine("Debug:");
            Console.Out.WriteLine(manager.Get("Text two", new { UserName = "******" }, debug: true));
            Console.Out.WriteLine();

            Console.Out.WriteLine(manager.Get("FormattedSwitch", new { Count = 7 }));

            Console.Out.WriteLine(manager.Get("Ref test 1", new { UserName = "******" }));
            Console.Out.WriteLine(manager.Get("Ref test 2", new { UserName = "******" }));

            Console.Out.WriteLine(manager.Get("Ref test 3", new { List = new[] { "Item 1", "Item 2", "Item 7", "Item 17" } }));
            Console.Out.WriteLine(manager.Get("Ref test 3", new { UserName = "******" }, ns: "Another"));

            string a = "Key";   /* @L10n @da-DK Foo @en-US Bar */
            string b = "Key 2"; // @L10n @da-DK Foo 2

            string.Format("Key 3" /* @L10n @da-DK Foo 3 */);



            string g = "Key"; /* @L10n @da-DK */


            string m = "Key" /* @L10n @en-US Goo */;

            //var extractor = new CStyleLanguageTextExtractor();
            //extractor.SourceFiles =
            //    new SourceFileList(@"C:\Users\niels.kuhnel\Stuff\Rebel\Rebel 5\I18n\i18n\Sandboxes\Localization\Sandbox.Localization.Tryout",
            //        new[] { "cs" }, new[] { "obj" }).GetFiles();

            //xml.Document = null;
            //xml.Put(extractor.Get().Select(x => new LocalizedTextState { Text = x }), TextMergeOptions.KeepUnused);
            //xml.Document.Save("Extracted.xml");


            Console.Out.WriteLine("Arithmetic");
            Console.Out.WriteLine(manager.Get("Arithmetic", new { Number = 11 }));

            Console.In.Read();
        }
Exemple #20
0
        protected override async Task <object> Insert <TEntity>(Expression <Func <TEntity> > content, string table, bool @async)
        {
            PublicHelper.CheckNull(content);

            TypeDescriptor typeDescriptor = EntityTypeContainer.GetDescriptor(typeof(TEntity));

            if (typeDescriptor.PrimaryKeys.Count > 1)
            {
                /* 对于多主键的实体,暂时不支持调用这个方法进行插入 */
                throw new NotSupportedException(string.Format("Can not call this method because entity '{0}' has multiple keys.", typeDescriptor.Definition.Type.FullName));
            }

            PrimitivePropertyDescriptor keyPropertyDescriptor = typeDescriptor.PrimaryKeys.FirstOrDefault();

            Dictionary <MemberInfo, Expression> insertColumns = InitMemberExtractor.Extract(content);

            DbTable dbTable = PublicHelper.CreateDbTable(typeDescriptor, table);

            DefaultExpressionParser expressionParser = typeDescriptor.GetExpressionParser(dbTable);
            DbInsertExpression      insertExp        = new DbInsertExpression(dbTable);

            object keyVal = null;

            foreach (var kv in insertColumns)
            {
                MemberInfo key = kv.Key;
                PrimitivePropertyDescriptor propertyDescriptor = typeDescriptor.GetPrimitivePropertyDescriptor(key);

                if (propertyDescriptor.IsAutoIncrement)
                {
                    throw new ChloeException(string.Format("Could not insert value into the identity column '{0}'.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("Can not insert value into the column '{0}', because it's mapping member has define a sequence.", propertyDescriptor.Column.Name));
                }

                if (propertyDescriptor.IsPrimaryKey)
                {
                    object val = ExpressionEvaluator.Evaluate(kv.Value);
                    if (val == null)
                    {
                        throw new ChloeException(string.Format("The primary key '{0}' could not be null.", propertyDescriptor.Property.Name));
                    }
                    else
                    {
                        keyVal = val;
                        insertExp.InsertColumns.Add(propertyDescriptor.Column, DbExpression.Parameter(keyVal));
                        continue;
                    }
                }

                insertExp.InsertColumns.Add(propertyDescriptor.Column, expressionParser.Parse(kv.Value));
            }

            foreach (var item in typeDescriptor.PrimitivePropertyDescriptors.Where(a => a.HasSequence()))
            {
                DbMethodCallExpression getNextValueForSequenceExp = PublicHelper.MakeNextValueForSequenceDbExpression(item, dbTable.Schema);
                insertExp.InsertColumns.Add(item.Column, getNextValueForSequenceExp);
            }

            if (keyPropertyDescriptor != null)
            {
                //主键为空并且主键又不是自增列
                if (keyVal == null && !keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence())
                {
                    throw new ChloeException(string.Format("The primary key '{0}' could not be null.", keyPropertyDescriptor.Property.Name));
                }
            }

            if (keyPropertyDescriptor == null)
            {
                await this.ExecuteNonQuery(insertExp, @async);

                return(keyVal); /* It will return null if an entity does not define primary key. */
            }
            if (!keyPropertyDescriptor.IsAutoIncrement && !keyPropertyDescriptor.HasSequence())
            {
                await this.ExecuteNonQuery(insertExp, @async);

                return(keyVal);
            }

            insertExp.Returns.Add(keyPropertyDescriptor.Column);

            IDbExpressionTranslator translator    = this.DatabaseProvider.CreateDbExpressionTranslator();
            DbCommandInfo           dbCommandInfo = translator.Translate(insertExp);

            object ret = this.Session.ExecuteScalar(dbCommandInfo.CommandText, dbCommandInfo.GetParameters());

            if (ret == null || ret == DBNull.Value)
            {
                throw new ChloeException("Unable to get the identity/sequence value.");
            }

            ret = PublicHelper.ConvertObjectType(ret, typeDescriptor.AutoIncrement.PropertyType);
            return(ret);
        }