Example #1
0
        // Cross Join
        private void AppendCrossJoin(ISqlBuilder jf, DbExpression exp, TableAliasCache aliases)
        {
            if (!_appendedKeyword)
            {
                jf.AppendNewLine();
                jf.Append(_keywordName);
                _appendedKeyword = true;
            }
            else
            {
                jf.Append(',');
                jf.AppendNewLine();
                jf.Append("     ");
            }

            LambdaExpression lambdaExp = exp.Expressions[1] as LambdaExpression;
            Type             type      = lambdaExp.Parameters[1].Type;
            var typeRuntime            = TypeRuntimeInfoCache.GetRuntimeInfo(type);

            jf.Append(' ');
            jf.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary);

            string alias = aliases.GetTableAlias(lambdaExp.Parameters[1]);

            jf.Append(' ');
            jf.Append(alias);
        }
Example #2
0
        // Cross Join
        private void AppendCrossJoin(ISqlBuilder builder, DbExpression exp, TableAliasCache aliases)
        {
            LambdaExpression lambdaExp = exp.Expressions[1] as LambdaExpression;
            Type             type      = lambdaExp.Parameters[1].Type;
            var typeRuntime            = TypeRuntimeInfoCache.GetRuntimeInfo(type);

            builder.Append(' ');
            builder.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary);

            string alias = aliases.GetTableAlias(lambdaExp.Parameters[1]);

            builder.Append(' ');
            builder.Append(alias);
            builder.Append(' ');
        }
Example #3
0
        // 获取 LEFT JOIN / INNER JOIN 子句关联表的的别名
        private void PrepareLfInJoinAlias(DbExpression exp, TableAliasCache aliases)
        {
            Type   type = exp.Expressions[0].Type.GetGenericArguments()[0];
            string name = TypeRuntimeInfoCache.GetRuntimeInfo(type).TableName;

            // on a.Name equals b.Name 或 on new{ Name = a.Name,Id=a.Id } equals new { Name = b.Name,Id=b.Id }
            LambdaExpression left  = exp.Expressions[1] as LambdaExpression;
            LambdaExpression right = exp.Expressions[2] as LambdaExpression;

            if (left.Body.NodeType == ExpressionType.New)
            {
                NewExpression body1 = left.Body as NewExpression;
                NewExpression body2 = right.Body as NewExpression;
                for (int index = 0; index < body1.Arguments.Count; ++index)
                {
                    aliases.GetTableAlias(body1.Arguments[index]);
                }
                for (int index = 0; index < body2.Arguments.Count; ++index)
                {
                    string alias = aliases.GetTableAlias(body2.Arguments[index]);
                    // 记录显示指定的LEFT JOIN 表别名
                    aliases.AddOrUpdateJoinTableAlias(name, alias);
                }
            }
            else if (left.Body.NodeType == ExpressionType.MemberInit)
            {
                MemberInitExpression body1 = left.Body as MemberInitExpression;
                MemberInitExpression body2 = right.Body as MemberInitExpression;
                for (int index = 0; index < body1.Bindings.Count; ++index)
                {
                    aliases.GetTableAlias((body1.Bindings[index] as MemberAssignment).Expression);
                }
                for (int index = 0; index < body2.Bindings.Count; ++index)
                {
                    string alias = aliases.GetTableAlias((body2.Bindings[index] as MemberAssignment).Expression);
                    // 记录显示指定的LEFT JOIN 表别名
                    aliases.AddOrUpdateJoinTableAlias(name, alias);
                }
            }
            else
            {
                aliases.GetTableAlias(exp.Expressions[1]);
                string alias = aliases.GetTableAlias(exp.Expressions[2]);
                // 记录显示指定的LEFT JOIN 表别名
                aliases.AddOrUpdateJoinTableAlias(name, alias);
            }
        }
        // 添加额外列,用来判断整个(左)连接记录是否为空
        private void AppendNullColumn(System.Reflection.MemberInfo member, string alias)
        {
            TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(member.DeclaringType);
            var             foreignKey  = typeRuntime.GetInvokerAttribute <ForeignKeyAttribute>(member.Name);
            string          keyName     = foreignKey.OuterKeys[0];

            _builder.Append("CASE WHEN ");
            _builder.AppendMember(alias, keyName);
            _builder.Append(" IS NULL THEN NULL ELSE ");
            _builder.AppendMember(alias, keyName);
            _builder.Append(" END");

            // 选择字段
            string newName = AddColumn(_columns, Constant.NAVIGATIONSPLITONNAME);

            //_builder.Append(caseWhen);
            _builder.AppendAs(newName);
            _builder.Append(',');
            _builder.AppendNewLine();
        }
        // 选择所有的字段
        private Expression VisitAllMember(Type type, string alias, Expression node = null)
        {
            if (_groupBy != null && node != null && node.IsGrouping())
            {
                // select g.Key
                LambdaExpression keySelector = _groupBy.Expressions[0] as LambdaExpression;
                return(this.Visit(keySelector.Body));
            }
            else
            {
                TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                Dictionary <string, MemberInvokerBase> invokers = typeRuntime.Invokers;

                foreach (var m in invokers)
                {
                    var invoker = m.Value;
                    if (invoker != null && invoker.Column != null && invoker.Column.NoMapped)
                    {
                        continue;
                    }
                    if (invoker != null && invoker.ForeignKey != null)
                    {
                        continue;                                                // 不加载导航属性
                    }
                    if (invoker.Member.MemberType == System.Reflection.MemberTypes.Method)
                    {
                        continue;
                    }

                    _builder.AppendMember(alias, invoker.Member.Name);

                    // 选择字段
                    string newName = AddColumn(_columns, invoker.Member.Name);
                    _builder.AppendAs(newName);
                    _builder.Append(",");
                    _builder.AppendNewLine();
                }
            }

            return(node);
        }
Example #6
0
        /// <summary>
        /// 获取指定成员的 <see cref="ColumnAttribute"/>
        /// </summary>
        public virtual ColumnAttribute GetColumnAttribute(MemberInfo member, Type runtimeType)
        {
            Type dataType = TypeUtils.GetDataType(member);

            if (dataType == null)
            {
                return(null);
            }

            ColumnAttribute column = null;
            Type            type   = runtimeType != null ? runtimeType : (member.ReflectedType != null ? member.ReflectedType : member.DeclaringType);

            if (type != null && !TypeUtils.IsAnonymousType(type))
            {
                TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                var             invoker     = typeRuntime.GetInvoker(member.Name);
                if (invoker != null)
                {
                    column = invoker.Column;
                }
            }

            return(column);
        }
        // 遍历 Include 包含的导航属性
        private void VisitInclude()
        {
            if (_include == null || _include.Count == 0)
            {
                return;
            }

            foreach (var dbExpression in _include)
            {
                Expression exp = dbExpression.Expressions[0];
                if (exp == null)
                {
                    continue;
                }

                if (exp.NodeType == ExpressionType.Lambda)
                {
                    exp = (exp as LambdaExpression).Body;
                }
                MemberExpression memberExpression = exp as MemberExpression;
                if (memberExpression == null)
                {
                    throw new XFrameworkException("Include expression body must be 'MemberExpression'.");
                }

                // 例:Include(a => a.Client.AccountList[0].Client)
                // 解析导航属性链
                List <Expression> chain = new List <Expression>();
                while (memberExpression != null)
                {
                    // a.Client 要求 <Client> 必须标明 ForeignKeyAttribute
                    TypeRuntimeInfo     typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(memberExpression.Expression.Type);
                    ForeignKeyAttribute attribute   = typeRuntime.GetInvokerAttribute <ForeignKeyAttribute>(memberExpression.Member.Name);
                    if (attribute == null)
                    {
                        throw new XFrameworkException("Include member {{{0}}} must mark 'ForeignKeyAttribute'.", memberExpression);
                    }

                    MemberExpression m = null;
                    chain.Add(memberExpression);
                    if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess)
                    {
                        m = (MemberExpression)memberExpression.Expression;
                    }
                    else if (memberExpression.Expression.NodeType == ExpressionType.Call)
                    {
                        m = (memberExpression.Expression as MethodCallExpression).Object as MemberExpression;
                    }

                    //var m = memberExpression.Expression as MemberExpression;
                    if (m == null)
                    {
                        chain.Add(memberExpression.Expression);
                    }
                    memberExpression = m;
                }

                // 生成导航属性描述信息
                string keyName = string.Empty;
                for (int i = chain.Count - 1; i >= 0; i--)
                {
                    Expression expression = chain[i];
                    memberExpression = expression as MemberExpression;
                    if (memberExpression == null)
                    {
                        continue;
                    }
                    //{
                    //    keyName = expression.Type.Name;
                    //    continue;
                    //}

                    //keyName = keyName + "." + memberExpression.Member.Name;
                    keyName = memberExpression.GetKeyWidthoutAnonymous(true);
                    if (!_navigations.ContainsKey(keyName))
                    {
                        // fix issue# XC 列占一个位
                        Navigation descriptor = new Navigation(keyName, memberExpression.Member);
                        descriptor.Start      = i == 0 ? _columns.Count : -1;           //_columns.Count;
                        descriptor.FieldCount = i == 0 ? (GetFieldCount(exp) + 1) : -1; //i == 0 ? (GetFieldCount(exp) + 1) : 1;//-1;
                        _navigations.Add(keyName, descriptor);
                    }
                }

                this.VisitNavigation(memberExpression, true);
            }
        }
        // {new App() {Id = p.Id}}
        private Expression VisitMemberInitImpl(MemberInitExpression node, bool topBinding)
        {
            // 如果有一对多的导航属性会产生嵌套的SQL,这时需要强制主表选择的列里面必须包含导航外键
            // TODO #对 Bindings 进行排序,保证导航属性的赋值一定要最后面#
            // 未实现,在书写表达式时人工保证 ##

            if (node.NewExpression != null)
            {
                this.VisitNewImpl(node.NewExpression);
            }
            if (_navChainHopper.Count == 0)
            {
                _navChainHopper.Add(node.Type.Name);
            }

            for (int i = 0; i < node.Bindings.Count; i++)
            {
                MemberAssignment binding = node.Bindings[i] as MemberAssignment;
                if (binding == null)
                {
                    throw new XFrameworkException("Only 'MemberAssignment' binding supported.");
                }

                Type propertyType = (node.Bindings[i].Member as System.Reflection.PropertyInfo).PropertyType;
                bool isNavigation = !TypeUtils.IsPrimitiveType(propertyType);

                #region 一般属性

                // 非导航属性
                if (!isNavigation)
                {
                    if (binding.Expression.CanEvaluate())
                    {
                        _builder.Append(binding.Expression.Evaluate().Value, binding.Member, node.Type);
                    }
                    else
                    {
                        base.VisitMemberBinding(binding);
                    }

                    // 选择字段
                    string newName = AddColumn(_columns, binding.Member.Name);
                    // 添加字段别名
                    _builder.AppendAs(newName);
                    _builder.Append(',');
                    _builder.AppendNewLine();
                }

                #endregion

                #region 导航属性

                else
                {
                    // 非显式指定的导航属性需要有 ForeignKeyAttribute
                    if (binding.Expression.NodeType == ExpressionType.MemberAccess && binding.Expression.Acceptable())
                    {
                        TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(binding.Member.DeclaringType);
                        var             attribute   = typeRuntime.GetInvokerAttribute <ForeignKeyAttribute>(binding.Member.Name);
                        if (attribute == null)
                        {
                            throw new XFrameworkException("Complex property {{{0}}} must mark 'ForeignKeyAttribute' ", binding.Member.Name);
                        }
                    }

                    // 生成导航属性描述集合,以类名.属性名做为键值
                    int    n       = _navChainHopper.Count;
                    string keyName = _navChainHopper.Count > 0 ? _navChainHopper[_navChainHopper.Count - 1] : string.Empty;
                    keyName = !string.IsNullOrEmpty(keyName) ? keyName + "." + binding.Member.Name : binding.Member.Name;
                    Navigation descriptor = new Navigation(keyName, binding.Member);
                    if (!_navigations.ContainsKey(keyName))
                    {
                        // fix issue# XC 列占一个位
                        descriptor.Start      = _columns.Count;
                        descriptor.FieldCount = GetFieldCount(binding.Expression) + (binding.Expression.NodeType == ExpressionType.MemberAccess && binding.Expression.Acceptable() ? 1 : 0);
                        _navigations.Add(keyName, descriptor);
                        _navChainHopper.Add(keyName);
                    }

                    // 1.不显式指定导航属性,例:a.Client.ClientList
                    // 2.表达式里显式指定导航属性,例:b
                    if (binding.Expression.NodeType == ExpressionType.MemberAccess)
                    {
                        this.VisitNavigation(binding.Expression as MemberExpression, binding.Expression.Acceptable());
                    }
                    else if (binding.Expression.NodeType == ExpressionType.New)
                    {
                        this.VisitNewImpl(binding.Expression as NewExpression);
                    }
                    else if (binding.Expression.NodeType == ExpressionType.MemberInit)
                    {
                        this.VisitMemberInitImpl(binding.Expression as MemberInitExpression, false);
                    }

                    // 恢复访问链
                    // 在访问导航属性时可能是 Client.CloudServer,这时要恢复为 Client,以保证能访问 Client 的下一个导航属性
                    if (_navChainHopper.Count != n)
                    {
                        _navChainHopper.RemoveAt(_navChainHopper.Count - 1);
                    }
                }

                #endregion

                base._visitedMember.Clear();
            }

            return(node);
        }
        // LEFT OR INNER JOIN
        private void AppendLfInJoin(ISqlBuilder jf, ISqlBuilder wf, ISqlBuilder on, DbExpression exp, TableAliasCache aliases)
        {
            bool             useExists = false;
            LambdaExpression left      = exp.Expressions[1] as LambdaExpression;
            LambdaExpression right     = exp.Expressions[2] as LambdaExpression;
            NewExpression    body1     = left.Body as NewExpression;
            NewExpression    body2     = right.Body as NewExpression;

            // t0(t1)
            string alias = body1 == null
                ? aliases.GetTableAlias(exp.Expressions[2])
                : aliases.GetTableAlias(right.Parameters[0]);//(body2.Arguments[0]);

            IDbQueryable sQuery = (IDbQueryable)((exp.Expressions[0] as ConstantExpression).Value);

            if (sQuery.DbExpressions.Count == 1 && sQuery.DbExpressions[0].DbExpressionType == DbExpressionType.GetTable)
            {
                useExists = true;
                if ((wf != null && wf.Length > 0) || (on != null && on.Length > 0))
                {
                    wf.AppendNewLine();
                    if (wf != null && wf.Length > 0)
                    {
                        wf.Append("AND ");
                    }
                }

                wf.Append("EXISTS(");
                wf.Indent += 1;
                wf.AppendNewLine();
                wf.Append("SELECT 1 FROM ");

                Type type        = exp.Expressions[0].Type.GetGenericArguments()[0];
                var  typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                wf.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary);
                wf.Append(' ');
                wf.Append(alias);

                wf.AppendNewLine();
                wf.Append("WHERE ");
            }
            else
            {
                useExists = true;
                if ((wf != null && wf.Length > 0) || (on != null && on.Length > 0))
                {
                    wf.AppendNewLine();
                    if (wf != null && wf.Length > 0)
                    {
                        wf.Append("AND ");
                    }
                }

                wf.Append("EXISTS(");
                wf.Indent += 1;
                wf.AppendNewLine();
                wf.Append("SELECT 1 FROM(");
                var cmd2 = sQuery.Resolve(wf.Indent + 1, false, wf.Parameters);
                wf.Append(cmd2.CommandText);
                wf.AppendNewLine();
                wf.Append(')');
                wf.Append(' ');
                wf.Append(alias);
                wf.Append(" WHERE ");
            }

            ISqlBuilder builder = useExists ? wf : on;

            if (body1 == null)
            {
                builder.AppendMember(aliases, left.Body.ReduceUnary());
                builder.Append(" = ");
                builder.AppendMember(aliases, right.Body.ReduceUnary());
            }
            else
            {
                for (int index = 0; index < body1.Arguments.Count; ++index)
                {
                    builder.AppendMember(aliases, body1.Arguments[index]);
                    builder.Append(" = ");
                    builder.AppendMember(aliases, body2.Arguments[index]);
                    if (index < body1.Arguments.Count - 1)
                    {
                        builder.Append(" AND ");
                    }
                }
            }

            //if (_where != null && _where.Expressions != null) this.AppendWhere(builder, right);

            if (useExists)
            {
                wf.Indent -= 1;
                wf.AppendNewLine();
                wf.Append(')');
            }
        }
Example #10
0
            //static ConstructorInfo _ctorXmlReader = typeof(XmlTextReader).GetConstructor(new[] { typeof(string), typeof(XmlNodeType), typeof(XmlParserContext) });
            //static ConstructorInfo _ctorSqlXml = typeof(System.Data.SqlTypes.SqlXml).GetConstructor(new[] { typeof(System.Xml.XmlTextReader) });

            internal static Func <IDataRecord, object> GetTypeDeserializer(Type type, IDataRecord reader, IDictionary <string, Column> columns = null, int start = 0, int?end = null)
            {
                //// specify a new assembly name
                //var assemblyName = new AssemblyName("Kitty");

                //// create assembly builder
                //var assemblyBuilder = AppDomain.CurrentDomain
                //  .DefineDynamicAssembly(assemblyName,
                //    AssemblyBuilderAccess.RunAndSave);

                //// create module builder
                //var moduleBuilder =
                //  assemblyBuilder.DefineDynamicModule(
                //    "KittyModule", "Kitty.exe");

                //// create type builder for a class
                //var typeBuilder =
                //  moduleBuilder.DefineType(
                //    "HelloKittyClass", TypeAttributes.Public);

                //// create method builder
                //var methodBuilder = typeBuilder.DefineMethod(
                //  "SayHelloMethod",
                //  MethodAttributes.Public | MethodAttributes.Static,
                //  typeof(object),
                //  new Type[] { typeof(IDataRecord) });

                TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                DynamicMethod   method      = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), typeof(object), new Type[] { typeof(IDataRecord) }, true);
                //ILGenerator il = methodBuilder.GetILGenerator();
                ILGenerator il = method.GetILGenerator();

                il.DeclareLocal(typeof(int));
                il.DeclareLocal(type);
                il.DeclareLocal(typeof(object));

                il.Emit(OpCodes.Ldc_I4_0);
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Stloc_2);

                // 有参构造函数
                ConstructorInfo specializedConstructor = null;

                if (type.IsValueType)
                {
                    // 如果是值类型,则将值类型设置为空或者0
                    il.Emit(OpCodes.Ldloca_S, (byte)1);
                    il.Emit(OpCodes.Initobj, type);
                }
                else
                {
                    var ctor = typeRuntime.ConstructInvoker.Constructor;
                    if (ctor.GetParameters().Length > 0)
                    {
                        specializedConstructor = ctor;
                    }
                    else
                    {
                        // 如果不是匿名类或者只有无参构造函数,则new一个对象
                        il.Emit(OpCodes.Newobj, ctor);
                        il.Emit(OpCodes.Stloc_1);
                    }
                }

                // try #####
                il.BeginExceptionBlock();
                if (specializedConstructor == null)
                {
                    il.Emit(OpCodes.Ldloc_1);                                 // [target]
                }
                // stack is now [target]
                Label finishLabel      = il.DefineLabel();
                Label loadNullLabel    = il.DefineLabel();
                int   enumDeclareLocal = -1;

                if (end == null)
                {
                    end = reader.FieldCount;
                }
                for (int index = start; index < end; index++)
                {
                    // 找出对应DataReader中的字段名
                    string memberName = reader.GetName(index);
                    if (columns != null)
                    {
                        Column column = null;
                        columns.TryGetValue(memberName, out column);
                        memberName = column != null ? column.Name : string.Empty;
                    }

                    // 本地变量赋值
                    il.Emit(OpCodes.Ldc_I4, index);                             // [target][index]
                    il.Emit(OpCodes.Stloc_0);                                   // [target]
                    //il.Emit(OpCodes.Ldnull);                                    // [target][null]
                    //il.Emit(OpCodes.Stloc_2);                                   // [target]

                    // 如果导航属性分割列=DbNull,那么此导航属性赋空值
                    if (memberName == Constant.NAVIGATIONSPLITONNAME)
                    {
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Ldc_I4, index);
                        il.Emit(OpCodes.Callvirt, _isDBNull);
                        il.Emit(OpCodes.Brtrue_S, loadNullLabel);
                    }

                    var invoker = typeRuntime.GetInvoker(memberName);
                    if (invoker == null)
                    {
                        continue;
                    }

                    if (specializedConstructor == null)
                    {
                        il.Emit(OpCodes.Dup);                                   // stack is now [target][target]
                    }
                    Type       columnType    = reader.GetFieldType(index);
                    Type       memberType    = invoker.DataType;
                    Label      isDbNullLabel = il.DefineLabel();
                    Label      nextLoopLabel = il.DefineLabel();
                    MethodInfo readMethod    = GetReaderMethod(columnType);

                    // 判断字段是否是 DbNull
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldc_I4, index);
                    il.Emit(OpCodes.Callvirt, _isDBNull);
                    il.Emit(OpCodes.Brtrue, isDbNullLabel);

                    // =>DataReader.Getxx(index)
                    il.Emit(OpCodes.Ldarg_0);                                   // stack is now [target][target][reader]
                    il.Emit(OpCodes.Ldc_I4, index);                             // stack is now [target][target][reader][index]
                    il.Emit(OpCodes.Callvirt, readMethod);                      // stack is now [target][target][value-or-object]

                    //// =>object = value,记录当前处理的值
                    //// 除了string类型之外,其它的都需要要装箱,这里会有性能损失,100w笔记录大概会损失0.8s~
                    //bool useBoxed = readMethod != _getValue && columnType != typeof(string);
                    //il.Emit(OpCodes.Dup);                                       // stack is now [target][target][value-or-object][value-or-object]
                    //if (useBoxed) il.Emit(OpCodes.Box, columnType);             // stack is now [target][target][value-or-object][value-as-object]
                    //else il.Emit(OpCodes.Castclass, typeof(object));            // stack is now [target][target][value][value-as-object]
                    //il.Emit(OpCodes.Stloc_2);                                   // stack is now [target][target][value-or-object]

                    if (memberType == typeof(char) || memberType == typeof(char?))
                    {
                        il.EmitCall(OpCodes.Call, memberType == typeof(char) ? _readChar : _readNullChar, null);    // stack is now [target][target][typed-value]
                    }
                    else
                    {
                        // unbox nullable enums as the primitive, i.e. byte etc
                        var nullUnderlyingType = Nullable.GetUnderlyingType(memberType);
                        var unboxType          = nullUnderlyingType != null && nullUnderlyingType.IsEnum ? nullUnderlyingType : memberType;

                        if (unboxType.IsEnum)
                        {
                            Type numericType = Enum.GetUnderlyingType(unboxType);
                            if (columnType != typeof(string))
                            {
                                BoxConvert(il, columnType, unboxType, numericType);
                            }
                            else
                            {
                                if (enumDeclareLocal == -1)
                                {
                                    enumDeclareLocal = il.DeclareLocal(typeof(string)).LocalIndex;
                                }
                                il.Emit(OpCodes.Castclass, typeof(string));         // stack is now [target][target][string]
                                il.StoreLocal(enumDeclareLocal);                    // stack is now [target][target]
                                il.Emit(OpCodes.Ldtoken, unboxType);                // stack is now [target][target][enum-type-token]
                                il.EmitCall(OpCodes.Call, _typeFromHandle, null);   // stack is now [target][target][enum-type]
                                il.LoadLocal(enumDeclareLocal);                     // stack is now [target][target][enum-type][string]
                                il.Emit(OpCodes.Ldc_I4_1);                          // stack is now [target][target][enum-type][string][true]
                                il.EmitCall(OpCodes.Call, _enumParse, null);        // stack is now [target][target][enum-as-object]
                                il.Emit(OpCodes.Unbox_Any, unboxType);              // stack is now [target][target][typed-value]
                            }

                            if (nullUnderlyingType != null)
                            {
                                var ctor = memberType.GetConstructor(new[] { nullUnderlyingType });
                                il.Emit(OpCodes.Newobj, ctor);                      // stack is now [target][target][typed-value]
                            }
                        }
                        else if (memberType.FullName == _linqBinaryName)
                        {
                            var ctor = memberType.GetConstructor(new Type[] { typeof(byte[]) });
                            il.Emit(OpCodes.Unbox_Any, typeof(byte[]));             // stack is now [target][target][byte-array]
                            il.Emit(OpCodes.Newobj, ctor);                          // stack is now [target][target][binary]
                        }
                        else
                        {
                            TypeCode dataTypeCode = Type.GetTypeCode(columnType), unboxTypeCode = Type.GetTypeCode(unboxType);
                            bool     useOriginal = columnType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == Type.GetTypeCode(nullUnderlyingType);
                            // fix issue# oracle guid
                            useOriginal = useOriginal && !((nullUnderlyingType ?? unboxType) == typeof(Guid) && columnType == typeof(byte[]));


                            if (useOriginal)
                            {
                                if (readMethod == _getValue && unboxType != typeof(object))
                                {
                                    il.EmitCast(nullUnderlyingType ?? unboxType);   // stack is now [target][target][typed-value]
                                }
                            }
                            else
                            {
                                if (readMethod == _getValue && columnType.IsValueType)// stack is now [target][target][value]
                                {
                                    il.Emit(OpCodes.Unbox_Any, columnType);
                                }
                                // not a direct match; need to tweak the unbox
                                BoxConvert(il, columnType, nullUnderlyingType ?? unboxType, null);
                            }

                            if (nullUnderlyingType != null)
                            {
                                var ctor = unboxType.GetConstructor(new[] { nullUnderlyingType });
                                il.Emit(OpCodes.Newobj, ctor);                      // stack is now [target][target][typed-value]
                            }
                        }
                    }

                    if (specializedConstructor == null)
                    {
                        // Store the value in the property/field
                        if (invoker.MemberType == MemberTypes.Field)
                        {
                            il.Emit(OpCodes.Stfld, invoker.Member as FieldInfo);                                         // stack is now [target]
                        }
                        else
                        {
                            MethodInfo setMethod = (invoker as PropertyInvoker).SetMethod;
                            il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, setMethod);// stack is now [target]
                        }
                    }

                    il.Emit(OpCodes.Br_S, nextLoopLabel);                       // stack is now [target]


                    il.MarkLabel(isDbNullLabel);                                // incoming stack: [target][target]
                    if (specializedConstructor == null)
                    {
                        il.Emit(OpCodes.Pop);                                   // stack is now [target]
                    }
                    else
                    {
                        // DbNull,将NULL或者0推到栈顶
                        if (!invoker.DataType.IsValueType)
                        {
                            il.Emit(OpCodes.Ldnull);
                        }
                        else
                        {
                            int localIndex = il.DeclareLocal(invoker.DataType).LocalIndex;
                            il.LoadLocalAddress(localIndex);
                            il.Emit(OpCodes.Initobj, invoker.DataType);
                            il.LoadLocal(localIndex);
                        }
                    }


                    il.MarkLabel(nextLoopLabel);
                }

                if (specializedConstructor != null)
                {
                    il.Emit(OpCodes.Newobj, specializedConstructor);
                }
                il.Emit(OpCodes.Stloc_1);               // stack is empty

                // 直接跳到结束标签返回实体
                il.Emit(OpCodes.Br, finishLabel);

                // 将 null 赋值给实体
                il.MarkLabel(loadNullLabel);
                il.Emit(OpCodes.Pop);
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Stloc_1);


                il.MarkLabel(finishLabel);
                il.BeginCatchBlock(typeof(Exception));      // stack is Exception
                il.Emit(OpCodes.Ldloc_0);                   // stack is Exception, index
                il.Emit(OpCodes.Ldloc_2);                   // stack is Exception, index, value
                il.Emit(OpCodes.Ldarg_0);                   // stack is Exception, index, reader
                il.EmitCall(OpCodes.Call, _throwException, null);
                il.EndExceptionBlock();

                il.Emit(OpCodes.Ldloc_1);                   // stack is [rval]
                il.Emit(OpCodes.Ret);

                //// then create the whole class type
                //var helloKittyClassType = typeBuilder.CreateType();

                //// set entry point for this assembly
                //assemblyBuilder.SetEntryPoint(
                //  helloKittyClassType.GetMethod("SayHelloMethod"));

                //// save assembly
                //assemblyBuilder.Save("Kitty.exe");

                return((Func <IDataRecord, object>)method.CreateDelegate(typeof(Func <IDataRecord, object>)));
            }
Example #11
0
        /// <summary>
        /// 将 <see cref="IDataRecord"/> 上的当前行反序列化为实体
        /// </summary>
        /// <param name="prevModel">前一行数据</param>
        /// <param name="isThisLine">是否同一行数据</param>
        internal T Deserialize(object prevModel, out bool isThisLine)
        {
            isThisLine = false;

            #region 基元类型

            string name = _reader.GetName(0);
            if (TypeUtils.IsPrimitiveType(typeof(T)) || name == Constant.AUTOINCREMENTNAME)
            {
                if (_reader.IsDBNull(0))
                {
                    return(default(T));
                }

                var obj = _reader.GetValue(0);
                if (obj.GetType() != typeof(T))
                {
                    // fix#Nullable<T> issue
                    if (!typeof(T).IsGenericType)
                    {
                        obj = Convert.ChangeType(obj, typeof(T));
                    }
                    else
                    {
                        Type g = typeof(T).GetGenericTypeDefinition();
                        if (g != typeof(Nullable <>))
                        {
                            throw new NotSupportedException(string.Format("type {0} not suppored.", g.FullName));
                        }
                        obj = Convert.ChangeType(obj, Nullable.GetUnderlyingType(typeof(T)));
                    }
                }

                return((T)obj);
            }

            #endregion

            #region 动态类型

            if (typeof(T) == typeof(ExpandoObject) || typeof(T) == typeof(object))
            {
                ExpandoObject obj    = new ExpandoObject();
                var           result = ((IDictionary <string, object>)obj);
                for (int i = 0; i < _reader.FieldCount; i++)
                {
                    var value = _reader.GetValue(i);
                    if (value == DBNull.Value)
                    {
                        value = null;
                    }
                    result.Add(_reader.GetName(i), value);
                }
                return((dynamic)obj);
            }

            #endregion

            #region 实体类型

            T model = default(T);
            TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo <T>();

            if (_definition == null || _definition.Navigations == null || _definition.Navigations.Count == 0)
            {
                // 没有字段映射说明或者没有导航属性
                if (_modelDeserializer == null)
                {
                    _modelDeserializer = InternalTypeDeserializer.GetTypeDeserializer(typeof(T), _reader, _definition != null ? _definition.Columns : null, 0);
                }
                model = (T)_modelDeserializer(_reader);
            }
            else
            {
                // 第一层
                if (_modelDeserializer == null)
                {
                    _modelDeserializer = InternalTypeDeserializer.GetTypeDeserializer(typeof(T), _reader, _definition.Columns, 0, _definition.Navigations.MinIndex);
                }
                model = (T)_modelDeserializer(_reader);
                // 若有 1:n 的导航属性,判断当前行数据与上一行数据是否相同
                if (prevModel != null && _definition.HaveListNavigation)
                {
                    isThisLine = true;
                    foreach (var key in typeRuntime.KeyInvokers)
                    {
                        var invoker = key.Value;
                        var value1  = invoker.Invoke(prevModel);
                        var value2  = invoker.Invoke(model);
                        isThisLine = isThisLine && value1.Equals(value2);
                        if (!isThisLine)
                        {
                            // fix issue#换行时清空上一行的导航键缓存
                            _listNavigationKeys.Clear();
                            break;
                        }
                    }
                }

                // 递归导航属性
                this.Deserialize_Navigation(isThisLine ? prevModel : null, model, string.Empty, isThisLine);
            }

            return(model);

            #endregion
        }
 /// <summary>
 /// 取指定类型的运行时元数据
 /// </summary>
 /// <typeparam name="T">T</typeparam>
 /// <returns></returns>
 public static TypeRuntimeInfo GetRuntimeInfo <T>()
 {
     return(TypeRuntimeInfoCache.GetRuntimeInfo(typeof(T)));
 }
Example #13
0
        // LEFT OR INNER JOIN
        private void AppendLfInJoin(ISqlBuilder builder, DbExpression exp, TableAliasCache aliases)
        {
            builder.Append(' ');
            IDbQueryable sQuery = (IDbQueryable)((exp.Expressions[0] as ConstantExpression).Value);

            if (sQuery.DbExpressions.Count == 1 && sQuery.DbExpressions[0].DbExpressionType == DbExpressionType.GetTable)
            {
                Type type        = exp.Expressions[0].Type.GetGenericArguments()[0];
                var  typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                builder.AppendMember(typeRuntime.TableName, !typeRuntime.IsTemporary);
            }
            else
            {
                // 嵌套
                var cmd = sQuery.Resolve(builder.Indent + 1, false, builder.Parameters);
                builder.Append("(");
                builder.AppendNewLine(cmd.CommandText);
                builder.Append(')');
            }


            LambdaExpression left  = exp.Expressions[1] as LambdaExpression;
            LambdaExpression right = exp.Expressions[2] as LambdaExpression;

            // t0(t1)
            string alias = !(left.Body.NodeType == ExpressionType.New || left.Body.NodeType == ExpressionType.MemberInit)
                ? aliases.GetTableAlias(exp.Expressions[2])
                : aliases.GetTableAlias(right.Parameters[0]);//(body2.Arguments[0]);

            builder.Append(' ');
            builder.Append(alias);
            builder.Append(' ');

            // ON a.Name = b.Name AND a.Id = b.Id
            builder.Append("ON ");

            if (left.Body.NodeType == ExpressionType.New)
            {
                NewExpression body1 = left.Body as NewExpression;
                NewExpression body2 = right.Body as NewExpression;

                for (int index = 0; index < body1.Arguments.Count; ++index)
                {
                    builder.AppendMember(aliases, body1.Arguments[index]);
                    builder.Append(" = ");
                    builder.AppendMember(aliases, body2.Arguments[index]);
                    if (index < body1.Arguments.Count - 1)
                    {
                        builder.Append(" AND ");
                    }
                }
            }
            else if (left.Body.NodeType == ExpressionType.MemberInit)
            {
                MemberInitExpression body1 = left.Body as MemberInitExpression;
                MemberInitExpression body2 = right.Body as MemberInitExpression;

                for (int index = 0; index < body1.Bindings.Count; ++index)
                {
                    builder.AppendMember(aliases, (body1.Bindings[index] as MemberAssignment).Expression);
                    builder.Append(" = ");
                    builder.AppendMember(aliases, (body2.Bindings[index] as MemberAssignment).Expression);
                    if (index < body1.Bindings.Count - 1)
                    {
                        builder.Append(" AND ");
                    }
                }
            }
            else
            {
                builder.AppendMember(aliases, left.Body.ReduceUnary());
                builder.Append(" = ");
                builder.AppendMember(aliases, right.Body.ReduceUnary());
            }
        }
Example #14
0
        // 初始化自增列信息
        private void InitializeIdentity()
        {
            TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo <T>();

            _autoIncrement = typeRuntime.Invokers.FirstOrDefault(x => x.Value.Column != null && x.Value.Column.IsIdentity).Value;
        }
        // 添加导航属性关联
        protected override void AppendNavigation()
        {
            if (this.NavMembers == null || this.NavMembers.Count == 0)
            {
                return;
            }

            // 如果有一对多的导航属性,肯定会产生嵌套查询。那么内层查询别名肯定是t0,所以需要清掉
            if (this.HaveListNavigation)
            {
                _aliases = new TableAliasCache(_aliases.ObviousAlias);
            }
            //开始产生 USING 子句
            ISqlBuilder jf    = this.JoinFragment;
            int         index = -1;

            // 未生成USING子句
            if (_aliases.ObviousAlias <= 1)
            {
                jf.AppendNewLine();
                jf.Append(_keywordName);
            }
            else
            {
                jf.Append(',');
                jf.AppendNewLine();
            }

            foreach (var kvp in this.NavMembers)
            {
                index++;
                string              key         = kvp.Key;
                MemberExpression    m           = kvp.Value;
                TypeRuntimeInfo     typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(m.Expression.Type);
                ForeignKeyAttribute attribute   = typeRuntime.GetInvokerAttribute <ForeignKeyAttribute>(m.Member.Name);

                string innerKey   = string.Empty;
                string outerKey   = key;
                string innerAlias = string.Empty;

                if (!m.Expression.Acceptable())
                {
                    innerKey = m.Expression.NodeType == ExpressionType.Parameter
                        ? (m.Expression as ParameterExpression).Name
                        : (m.Expression as MemberExpression).Member.Name;
                }
                else
                {
                    MemberExpression mLeft = null;
                    if (m.Expression.NodeType == ExpressionType.MemberAccess)
                    {
                        mLeft = m.Expression as MemberExpression;
                    }
                    else if (m.Expression.NodeType == ExpressionType.Call)
                    {
                        mLeft = (m.Expression as MethodCallExpression).Object as MemberExpression;
                    }
                    string name = TypeRuntimeInfoCache.GetRuntimeInfo(mLeft.Type).TableName;
                    innerAlias = _aliases.GetJoinTableAlias(name);

                    if (string.IsNullOrEmpty(innerAlias))
                    {
                        string keyLeft = mLeft.GetKeyWidthoutAnonymous();
                        if (this.NavMembers.ContainsKey(keyLeft))
                        {
                            innerKey = keyLeft;
                        }
                    }
                }

                string alias1 = !string.IsNullOrEmpty(innerAlias) ? innerAlias : _aliases.GetTableAlias(innerKey);
                string alias2 = _aliases.GetTableAlias(outerKey);

                // 补充与USING字符串同等间距的空白
                if (_aliases.ObviousAlias > 1 || index > 0)
                {
                    jf.Append("     ");
                }

                Type type         = m.Type;
                var  typeRumtime2 = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                if (type.IsGenericType)
                {
                    type = type.GetGenericArguments()[0];
                }
                jf.Append(' ');
                jf.AppendMember(typeRumtime2.TableName, typeRumtime2.IsTemporary);
                jf.Append(' ');
                jf.Append(alias2);

                if (_onPhrase.Length > 0)
                {
                    _onPhrase.Append(" AND ");
                }
                for (int i = 0; i < attribute.InnerKeys.Length; i++)
                {
                    _onPhrase.Append(alias1);
                    _onPhrase.Append('.');
                    _onPhrase.AppendMember(attribute.InnerKeys[i]);
                    _onPhrase.Append(" = ");
                    _onPhrase.Append(alias2);
                    _onPhrase.Append('.');
                    _onPhrase.AppendMember(attribute.OuterKeys[i]);
                }

                if (index < this.NavMembers.Count - 1)
                {
                    jf.Append(',');
                    jf.AppendNewLine();
                }
            }
        }
Example #16
0
        // 反序列化导航属性
        // @prevLine 前一行数据
        // @isLine   是否同一行数据<同一父级>
        void Deserialize_Navigation(object prevModel, object model, string typeName, bool isThisLine)
        {
            // CRM_SaleOrder.Client
            // CRM_SaleOrder.Client.AccountList
            Type            type        = model.GetType();
            TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);

            if (string.IsNullOrEmpty(typeName))
            {
                typeName = type.Name;
            }

            foreach (var kvp in _definition.Navigations)
            {
                int start      = -1;
                int end        = -1;
                var descriptor = kvp.Value;
                if (descriptor.FieldCount > 0)
                {
                    start = descriptor.Start;
                    end   = descriptor.Start + descriptor.FieldCount;
                }

                string keyName = typeName + "." + descriptor.Name;
                if (keyName != kvp.Key)
                {
                    continue;
                }

                var navInvoker = typeRuntime.GetInvoker(descriptor.Name);
                if (navInvoker == null)
                {
                    continue;
                }

                Type navType = navInvoker.DataType;
                Func <IDataRecord, object> deserializer   = null;
                TypeRuntimeInfo            navTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(navType);
                object navCollection = null;
                //if (navType.IsGenericType && navTypeRuntime.GenericTypeDefinition == typeof(List<>))
                if (TypeUtils.IsCollectionType(navType))
                {
                    // 1:n关系,导航属性为 List<T>
                    navCollection = navInvoker.Invoke(model);
                    if (navCollection == null)
                    {
                        // new 一个列表类型,如果导航属性定义为接口,则默认使用List<T>来实例化
                        TypeRuntimeInfo navTypeRuntime2 = navType.IsInterface
                            ? TypeRuntimeInfoCache.GetRuntimeInfo(typeof(List <>).MakeGenericType(navTypeRuntime.GenericArguments[0]))
                            : navTypeRuntime;
                        navCollection = navTypeRuntime2.ConstructInvoker.Invoke();
                        navInvoker.Invoke(model, navCollection);
                    }
                }

                if (!_deserializers.TryGetValue(keyName, out deserializer))
                {
                    deserializer            = InternalTypeDeserializer.GetTypeDeserializer(navType.IsGenericType ? navTypeRuntime.GenericArguments[0] : navType, _reader, _definition.Columns, start, end);
                    _deserializers[keyName] = deserializer;
                }

                // 如果整个导航链中某一个导航属性为空,则跳出递归
                object navModel = deserializer(_reader);
                if (navModel != null)
                {
                    if (navCollection == null)
                    {
                        // 非集合型导航属性
                        navInvoker.Invoke(model, navModel);
                        //
                        //
                        //
                    }
                    else
                    {
                        // 集合型导航属性
                        if (prevModel != null && isThisLine)
                        {
                            #region 合并列表

                            // 判断如果属于同一个主表,则合并到上一行的当前明细列表
                            // 例:CRM_SaleOrder.Client.AccountList
                            string[]          keys           = keyName.Split('.');
                            TypeRuntimeInfo   curTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo <T>();
                            Type              curType        = curTypeRuntime.Type;
                            MemberInvokerBase curInvoker     = null;
                            object            curModel       = prevModel;

                            for (int i = 1; i < keys.Length; i++)
                            {
                                curInvoker = curTypeRuntime.GetInvoker(keys[i]);
                                curModel   = curInvoker.Invoke(curModel);
                                if (curModel == null)
                                {
                                    continue;
                                }

                                curType        = curModel.GetType();
                                curTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(curType);

                                // <<<<<<<<<<< 一对多对多关系 >>>>>>>>>>
                                if (curType.IsGenericType && i != keys.Length - 1)
                                {
                                    curTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(curType);
                                    //if (curTypeRuntime.GenericTypeDefinition == typeof(List<>))
                                    if (TypeUtils.IsCollectionType(curType))
                                    {
                                        var invoker = curTypeRuntime.GetInvoker("get_Count");
                                        int count   = Convert.ToInt32(invoker.Invoke(curModel));    // List.Count
                                        if (count > 0)
                                        {
                                            var invoker2 = curTypeRuntime.GetInvoker("get_Item");
                                            curModel       = invoker2.Invoke(curModel, count - 1);  // List[List.Count-1]
                                            curTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(curModel.GetType());
                                        }
                                        else
                                        {
                                            // user.Roles.RoleFuncs=>Roles 列表有可能为空
                                            curModel = null;
                                            break;
                                        }
                                    }
                                }
                            }


                            if (curModel != null)
                            {
                                // 如果有两个以上的一对多关系的导航属性,那么在加入列表之前就需要剔除重复的实体


                                bool isAny = false;
                                if (_definition.Navigations.Count > 1)
                                {
                                    if (_listNavigationCount == null)
                                    {
                                        _listNavigationCount = _definition.Navigations.Count(x => CheckCollectionNavigation(x.Value.Member));
                                    }
                                    if (_listNavigationCount != null && _listNavigationCount.Value > 1)
                                    {
                                        if (!_listNavigationKeys.ContainsKey(keyName))
                                        {
                                            _listNavigationKeys[keyName] = new HashSet <string>();
                                        }
                                        curTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(navModel.GetType());
                                        StringBuilder keyBuilder = new StringBuilder(64);

                                        foreach (var key in curTypeRuntime.KeyInvokers)
                                        {
                                            var invoker = key.Value;
                                            var value   = invoker.Invoke(navModel);
                                            keyBuilder.AppendFormat("{0}={1};", key.Key, (value ?? string.Empty).ToString());
                                        }
                                        string hash = keyBuilder.ToString();
                                        if (_listNavigationKeys[keyName].Contains(hash))
                                        {
                                            isAny = true;
                                        }
                                        else
                                        {
                                            _listNavigationKeys[keyName].Add(hash);
                                        }
                                    }
                                }

                                if (!isAny)
                                {
                                    // 如果列表中不存在,则添加到上一行的相同导航列表中去
                                    var myAddMethod = navTypeRuntime.GetInvoker("Add");
                                    myAddMethod.Invoke(curModel, navModel);
                                }
                            }

                            #endregion
                        }
                        else
                        {
                            // 此时的 navTypeRuntime 是 List<> 类型的运行时
                            // 先添加 List 列表
                            var myAddMethod = navTypeRuntime.GetInvoker("Add");
                            myAddMethod.Invoke(navCollection, navModel);

                            var           curTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(navModel.GetType());
                            StringBuilder keyBuilder     = new StringBuilder(64);

                            foreach (var key in curTypeRuntime.KeyInvokers)
                            {
                                var wrapper = key.Value;
                                var value   = wrapper.Invoke(navModel);
                                keyBuilder.AppendFormat("{0}={1};", key.Key, (value ?? string.Empty).ToString());
                            }
                            string hash = keyBuilder.ToString();
                            if (!_listNavigationKeys.ContainsKey(keyName))
                            {
                                _listNavigationKeys[keyName] = new HashSet <string>();
                            }
                            if (!_listNavigationKeys[keyName].Contains(hash))
                            {
                                _listNavigationKeys[keyName].Add(hash);
                            }
                        }
                    }

                    //if (navTypeRuntime.GenericTypeDefinition == typeof(List<>)) navTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(navTypeRuntime.GenericArguments[0]);
                    if (TypeUtils.IsCollectionType(navTypeRuntime.Type))
                    {
                        navTypeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(navTypeRuntime.GenericArguments[0]);
                    }
                    if (navTypeRuntime.NavInvokers.Count > 0)
                    {
                        Deserialize_Navigation(prevModel, navModel, keyName, isThisLine);
                    }
                }
            }
        }
Example #17
0
        // 访问导航属性
        protected virtual string VisitNavMember(Expression expression, string memberName = null)
        {
            // 表达式 => b.Client.Address.AddressName
            Expression node = expression;
            Stack <KeyValuePair <string, MemberExpression> > stack = null;
            string alias = string.Empty;

            while (node != null && node.Acceptable())
            {
                if (node.NodeType != ExpressionType.MemberAccess)
                {
                    break;
                }

                if (stack == null)
                {
                    stack = new Stack <KeyValuePair <string, MemberExpression> >();
                }
                MemberExpression memberExpression = node as MemberExpression;

                TypeRuntimeInfo     typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(memberExpression.Expression.Type);
                ForeignKeyAttribute attribute   = typeRuntime.GetInvokerAttribute <ForeignKeyAttribute>(memberExpression.Member.Name);
                if (attribute == null)
                {
                    break;
                }

                string key = memberExpression.GetKeyWidthoutAnonymous();
                stack.Push(new KeyValuePair <string, MemberExpression>(key, memberExpression));
                node = memberExpression.Expression;
                if (node.NodeType == ExpressionType.Call)
                {
                    node = (node as MethodCallExpression).Object;
                }
            }

            if (stack != null && stack.Count > 0)
            {
                while (stack != null && stack.Count > 0)
                {
                    KeyValuePair <string, MemberExpression> kvp = stack.Pop();
                    string           key  = kvp.Key;
                    MemberExpression m    = kvp.Value;
                    Type             type = m.Type;
                    if (type.IsGenericType)
                    {
                        type = type.GetGenericArguments()[0];
                    }

                    TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                    // 检查查询表达式是否显示指定该表关联
                    alias = _aliases.GetJoinTableAlias(typeRuntime.TableName);
                    if (string.IsNullOrEmpty(alias))
                    {
                        // 如果没有,则使用导航属性别名
                        alias = _aliases.GetNavigationTableAlias(key);
                        if (!_navMembers.ContainsKey(kvp.Key))
                        {
                            _navMembers.Add(kvp);
                        }
                    }

                    // 例: a.Client.ClientId
                    if (stack.Count == 0 && !string.IsNullOrEmpty(memberName))
                    {
                        _builder.AppendMember(alias, memberName);
                    }
                }
            }
            else
            {
                // => SelectMany 也会产生类似 'b.Client.Address.AddressName' 这样的表达式
                alias = _aliases.GetTableAlias(expression);
                _builder.AppendMember(alias, memberName);
            }

            // fix issue# Join 表达式显式指定导航属性时时,alias 为空
            return(alias);
        }
        // 添加导航属性关联
        protected virtual void AppendNavigation()
        {
            if (this._navMembers == null || this._navMembers.Count == 0)
            {
                return;
            }

            // 如果有一对多的导航属性,肯定会产生嵌套查询。那么内层查询别名肯定是t0,所以需要清掉
            if (this.HaveListNavigation)
            {
                _aliases = new TableAliasCache(_aliases.ObviousAlias);
            }
            //开始产生LEFT JOIN 子句
            ISqlBuilder builder = this.JoinFragment;

            foreach (var kvp in _navMembers)
            {
                string              key         = kvp.Key;
                MemberExpression    m           = kvp.Value;
                TypeRuntimeInfo     typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(m.Expression.Type);
                ForeignKeyAttribute attribute   = typeRuntime.GetInvokerAttribute <ForeignKeyAttribute>(m.Member.Name);

                string innerKey   = string.Empty;
                string outerKey   = key;
                string innerAlias = string.Empty;

                if (!m.Expression.Acceptable())
                {
                    innerKey = m.Expression.NodeType == ExpressionType.Parameter
                        ? (m.Expression as ParameterExpression).Name
                        : (m.Expression as MemberExpression).Member.Name;
                }
                else
                {
                    MemberExpression mLeft = null;
                    if (m.Expression.NodeType == ExpressionType.MemberAccess)
                    {
                        mLeft = m.Expression as MemberExpression;
                    }
                    else if (m.Expression.NodeType == ExpressionType.Call)
                    {
                        mLeft = (m.Expression as MethodCallExpression).Object as MemberExpression;
                    }
                    string name = TypeRuntimeInfoCache.GetRuntimeInfo(mLeft.Type).TableName;
                    innerAlias = _aliases.GetJoinTableAlias(name);

                    if (string.IsNullOrEmpty(innerAlias))
                    {
                        string keyLeft = mLeft.GetKeyWidthoutAnonymous();
                        if (_navMembers.ContainsKey(keyLeft))
                        {
                            innerKey = keyLeft;
                        }
                    }
                }

                string alias1 = !string.IsNullOrEmpty(innerAlias) ? innerAlias : _aliases.GetTableAlias(innerKey);
                string alias2 = _aliases.GetTableAlias(outerKey);


                builder.AppendNewLine();
                builder.Append("LEFT JOIN ");
                Type type = m.Type;
                if (type.IsGenericType)
                {
                    type = type.GetGenericArguments()[0];
                }
                var typeRuntime2 = TypeRuntimeInfoCache.GetRuntimeInfo(type);
                builder.AppendMember(typeRuntime2.TableName, !typeRuntime2.IsTemporary);
                builder.Append(" ");
                builder.Append(alias2);
                builder.Append(" ON ");
                for (int i = 0; i < attribute.InnerKeys.Length; i++)
                {
                    builder.Append(alias1);
                    builder.Append('.');
                    builder.AppendMember(attribute.InnerKeys[i]);
                    builder.Append(" = ");
                    builder.Append(alias2);
                    builder.Append('.');
                    builder.AppendMember(attribute.OuterKeys[i]);

                    if (i < attribute.InnerKeys.Length - 1)
                    {
                        builder.Append(" AND ");
                    }
                }
            }
        }