public ClassPropertyAssignment(ClassProperty property, Expression rhs)
 {
     ClassProperty = property;
     RightHandExpression = rhs;
     ExpressionType = ExpressionType.ClassPropertyAssignment;
     HasVar =  ClassProperty.HasVar || rhs.HasVar;
     expressionID = ClassProperty.ExpressionID + "=" + RightHandExpression.ExpressionID;
 }
        public ObjectPropertyAtom(IObjectInstance objectInstance, ClassProperty classProperty, bool hasChildObject)
            : base(objectInstance, classProperty)
        {
            _hasChildObject = hasChildObject;

            if (ClassProperty.CanRead)
            {
                // When the property is out of date, update it from the wrapped object.
                _depProperty = new Dependent(delegate
                {
                    object value = ClassProperty.GetObjectValue(ObjectInstance.WrappedObject);
                    if (_hasChildObject)
                    {
                        IObjectInstance oldChild = _child;
                        object oldValue = oldChild == null ? null : oldChild.WrappedObject;

                        _child = null;
                        IObjectInstance wrapper;
                        if (value == null)
                            wrapper = null;
                        else if (value == oldValue)
                        {
                            wrapper = oldChild;
                            _child = wrapper;
                        }
                        else
                        {
                            if (WrapObject(value, out wrapper))
                                _child = wrapper;
                        }
                        ClassProperty.SetUserOutput(ObjectInstance, wrapper);

                        if (oldChild != _child && oldChild != null)
                        {
                            ObjectInstance.Tree.RemoveKey(oldValue);
                            oldChild.Dispose();
                        }
                    }
                    else
                    {
                        ClassProperty.SetUserOutput(ObjectInstance, value);
                    }
                });
            }
        }
示例#3
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="classProperty"></param>
            /// <returns></returns>
            public static Func <TEntity, TResult> GetFunc(ClassProperty classProperty)
            {
                var func = (Func <TEntity, TResult>)null;

                if (cache.TryGetValue(classProperty.GetHashCode(), out func) == false)
                {
                    if (classProperty != null)
                    {
                        var typeOfEntity = typeof(TEntity);
                        var entity       = Expression.Parameter(typeOfEntity, "entity");
                        var body         = Expression.Convert(Expression.Call(entity, classProperty.PropertyInfo.GetMethod), typeof(TResult));

                        func = Expression
                               .Lambda <Func <TEntity, TResult> >(body, entity)
                               .Compile();
                    }

                    cache.TryAdd(classProperty.GetHashCode(), func);
                }
                return(func);
            }
示例#4
0
        public void InsertT <T>(T InValue) where T : Base
        {
            Assert.IsFalse(SQLite3DbHandle.Zero == handle);
            ClassProperty property = InValue.ClassPropertyInfos;

            stringBuilder.Remove(0, stringBuilder.Length);
            stringBuilder.Append("INSERT INTO ")
            .Append(property.ClassName)
            .Append(" VALUES(");

            int length = property.Infos.Length;

            for (int i = 0; i < length; i++)
            {
                stringBuilder.Append("\"").Append(property.Infos[i].GetValue(InValue, null)).Append("\", ");
            }
            stringBuilder.Remove(stringBuilder.Length - 2, 2);
            stringBuilder.Append(")");

            Exec(stringBuilder.ToString());
        }
            public long?Get(object input,
                            ClassProperty property)
            {
                var value = Convert.ToInt64(input);

                if (value > 0)
                {
                    return(value);
                }
                else
                {
                    if (property.PropertyInfo.PropertyType.IsNullable())
                    {
                        return(null);
                    }
                    else
                    {
                        return(default(long));
                    }
                }
            }
示例#6
0
        public void CreateTable <T>() where T : Base
        {
            Assert.IsFalse(SQLite3DbHandle.Zero == handle);

            ClassProperty classProperty = Base.GetPropertyInfos(typeof(T));

            stringBuilder.Remove(0, stringBuilder.Length);
            stringBuilder.Append("CREATE TABLE ")
            .Append(classProperty.ClassName)
            .Append("(");
            int length = classProperty.Infos.Length;

            for (int i = 0; i < length; ++i)
            {
                stringBuilder.Append(classProperty.Infos[i].Name);

                Type type = classProperty.Infos[i].PropertyType;

                if (type == typeof(int) || type == typeof(long))
                {
                    stringBuilder.Append(" INTEGER, ");
                }
                else if (type == typeof(float) || type == typeof(double))
                {
                    stringBuilder.Append(" REAL, ");
                }
                else if (type == typeof(string))
                {
                    stringBuilder.Append(" TEXT, ");
                }
                else
                {
                    stringBuilder.Append(" BLOB, ");
                }
            }
            stringBuilder.Remove(stringBuilder.Length - 2, 2);
            stringBuilder.Append(")");

            Exec(stringBuilder.ToString());
        }
示例#7
0
        public ReadOnlyClassProperty(ClassProperty property)
        {
            this.property = property;
            propertyType  = new ReadOnlyTypeReference(property.Type);
            if (property.EmptyAccessors != null)
            {
                getAccessor = new ReadOnlyClassAccessor(property.EmptyAccessors.GetAccessorVisibility);
                setAccessor = new ReadOnlyClassAccessor(property.EmptyAccessors.SetAccessorVisibility);
            }
            else
            {
                if (property.GetAccessor != null)
                {
                    getAccessor = new ReadOnlyClassAccessor(property.GetAccessor);
                }

                if (property.SetAccessor != null)
                {
                    setAccessor = new ReadOnlyClassAccessor(property.SetAccessor);
                }
            }
        }
        public void Read_class_properties()
        {
            var val = new NullableModel {
                Value = 12
            };
            var model = new ClassProperty {
                Nullable = val
            };
            var result = Read(model);

            result.Should().HaveCount(2);

            result[0].Attributes.Should().HaveCount(1);
            result[0].Attributes.ElementAt(0).Should().BeAssignableTo <RequiredAttribute>();
            result[0].Value.Should().Be(val);
            result[0].Path.Should().BeEquivalentTo(new[] { "nullable" });

            result[1].Attributes.Should().HaveCount(1);
            result[1].Attributes.ElementAt(0).Should().BeAssignableTo <RequiredAttribute>();
            result[1].Value.Should().Be(12);
            result[1].Path.Should().BeEquivalentTo(new[] { "nullable", "value" });
        }
示例#9
0
            /// <summary>
            ///
            /// </summary>
            /// <param name="classProperty"></param>
            /// <returns></returns>
            public static Action <TEntity, object> GetFunc(ClassProperty classProperty)
            {
                var func = (Action <TEntity, object>)null;

                if (cache.TryGetValue(classProperty.GetHashCode(), out func) == false)
                {
                    if (classProperty != null)
                    {
                        var entity    = Expression.Parameter(typeof(TEntity), "entity");
                        var value     = Expression.Parameter(typeof(object), "value");
                        var converted = Expression.Convert(value, classProperty.PropertyInfo.PropertyType);
                        var body      = (Expression)Expression.Call(entity, classProperty.PropertyInfo.SetMethod, converted);

                        func = Expression
                               .Lambda <Action <TEntity, object> >(body, entity, value)
                               .Compile();
                    }

                    cache.TryAdd(classProperty.GetHashCode(), func);
                }
                return(func);
            }
示例#10
0
        public override IQueryElement VisitWhere_value([NotNull] QueryGrammarParser.Where_valueContext context)
        {
            if (context.literal() != null)
            {
                IQueryElement literal = Visit(context.literal());
                return(literal);
            }
            else if (context.NAME() != null)
            {
                ClassProperty property = new ClassProperty();
                property.Name = context.NAME().GetText();

                if (context.child_value() != null)
                {
                    IQueryElement propertyChild = Visit(context.child_value());
                    property.Add(propertyChild);
                }
                return(property);
            }

            return(null);
        }
示例#11
0
        private PropertyDeclaration VisitClassProperty(ClassProperty property)
        {
            Ust     body = VisitPropertyValue(property.Value);
            IdToken name = null;

            if (property.Key is Identifier identifier)
            {
                name = VisitIdentifier(identifier);
            }
            else
            {
                if (property.Key is Literal literal)
                {
                    name = new IdToken(literal.StringValue ?? literal.Raw, GetTextSpan(literal));
                }
                else
                {
                    Logger.LogDebug($"Not implemented type of property key {property.Key.GetType()}"); // TODO
                }
            }

            return(new PropertyDeclaration(null, name, body, GetTextSpan(property)));
        }
示例#12
0
        private void DumpAutoProperty(ClassProperty property)
        {
            textWriter.Write(" {");

            if ((property.Access & PropertyAccess.Read) != PropertyAccess.None)
            {
                if (property.ReaderScope != property.Scope)
                {
                    textWriter.Write(" {0}", property.ReaderScope.ToString().ToLower());
                }
                textWriter.Write(" read;");
            }

            if ((property.Access & PropertyAccess.Write) != PropertyAccess.None)
            {
                if (property.WriterScope != property.Scope)
                {
                    textWriter.Write(" {0}", property.WriterScope.ToString().ToLower());
                }
                textWriter.Write(" write;");
            }

            textWriter.WriteLine(" }");
        }
示例#13
0
            public static Action <TEntity, object> GetFunc(ClassProperty property)
            {
                var func = (Action <TEntity, object>)null;

                // Try get from cache
                if (m_cache.TryGetValue(property.GetHashCode(), out func) == false)
                {
                    // Parameters
                    var entity = Expression.Parameter(typeof(TEntity), "entity");
                    var value  = Expression.Parameter(typeof(object), "value");

                    // Set the body
                    var converted = Expression.Convert(value, property.PropertyInfo.PropertyType);
                    var body      = (Expression)Expression.Call(entity, property.PropertyInfo.SetMethod, converted);

                    // Set the function value
                    func = Expression
                           .Lambda <Action <TEntity, object> >(body, entity, value)
                           .Compile();
                }

                // return the function
                return(func);
            }
示例#14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="commandParameterExpression"></param>
        /// <param name="paramProperty"></param>
        /// <param name="dbField"></param>
        /// <param name="valueType"></param>
        /// <param name="valueExpression"></param>
        /// <returns></returns>
        public static Expression GetPlainTypeToDbParametersForEnumCompiledFunction(Expression commandParameterExpression,
                                                                                   ClassProperty paramProperty,
                                                                                   DbField dbField,
                                                                                   Type valueType,
                                                                                   Expression valueExpression)
        {
            // DbType
            var dbType = IsPostgreSqlUserDefined(dbField) ? default :
                         paramProperty.GetDbType() ??
                         valueType.GetDbType() ??
                         (dbField != null ? new ClientTypeToDbTypeResolver().Resolve(dbField.Type) : null) ??
                         (DbType?)Converter.EnumDefaultDatabaseType;

                         // DbCommandExtension.CreateParameter
                         var methodInfo = GetDbCommandCreateParameterMethod();

                         return(Expression.Call(methodInfo, new Expression[]
            {
                commandParameterExpression,
                Expression.Constant(paramProperty.GetMappedName()),
                ConvertExpressionToTypeExpression(valueExpression, StaticType.Object),
                ConvertExpressionToNullableExpression(Expression.Constant(dbType), StaticType.DbType)
            }));
        }
 public int Set(int input, ClassProperty property)
 {
     return(input);
 }
示例#16
0
        public static void Run(TestHelper helper)
        {
            TextWriter output = helper.Output;

            output.Write("testing default values... ");
            output.Flush();

            {
                var v = new Base();
                TestHelper.Assert(!v.BoolFalse);
                TestHelper.Assert(v.BoolTrue);
                TestHelper.Assert(v.B == 1);
                TestHelper.Assert(v.S == 2);
                TestHelper.Assert(v.I == 3);
                TestHelper.Assert(v.L == 4);
                TestHelper.Assert(v.F == 5.1F);
                TestHelper.Assert(v.D == 6.2);
                TestHelper.Assert(v.Str.Equals("foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \u0007 \u0007"));
                TestHelper.Assert(v.NoDefault == null);
                TestHelper.Assert(v.ZeroI == 0);
                TestHelper.Assert(v.ZeroL == 0);
                TestHelper.Assert(v.ZeroF == 0);
                TestHelper.Assert(v.ZeroDotF == 0);
                TestHelper.Assert(v.ZeroD == 0);
                TestHelper.Assert(v.ZeroDotD == 0);
            }

            {
                var v = new Derived();
                TestHelper.Assert(!v.BoolFalse);
                TestHelper.Assert(v.BoolTrue);
                TestHelper.Assert(v.B == 1);
                TestHelper.Assert(v.S == 2);
                TestHelper.Assert(v.I == 3);
                TestHelper.Assert(v.L == 4);
                TestHelper.Assert(v.F == 5.1F);
                TestHelper.Assert(v.D == 6.2);
                TestHelper.Assert(v.Str.Equals("foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \u0007 \u0007"));
                TestHelper.Assert(v.C1 == Color.red);
                TestHelper.Assert(v.C2 == Color.green);
                TestHelper.Assert(v.C3 == Color.blue);
                TestHelper.Assert(v.Nc1 == Nested.Color.red);
                TestHelper.Assert(v.Nc2 == Nested.Color.green);
                TestHelper.Assert(v.Nc3 == Nested.Color.blue);
                TestHelper.Assert(v.NoDefault == null);
                TestHelper.Assert(v.ZeroI == 0);
                TestHelper.Assert(v.ZeroL == 0);
                TestHelper.Assert(v.ZeroF == 0);
                TestHelper.Assert(v.ZeroDotF == 0);
                TestHelper.Assert(v.ZeroD == 0);
                TestHelper.Assert(v.ZeroDotD == 0);
            }

            {
                var v = new BaseEx();
                TestHelper.Assert(!v.BoolFalse);
                TestHelper.Assert(v.BoolTrue);
                TestHelper.Assert(v.B == 1);
                TestHelper.Assert(v.S == 2);
                TestHelper.Assert(v.I == 3);
                TestHelper.Assert(v.L == 4);
                TestHelper.Assert(v.F == 5.1F);
                TestHelper.Assert(v.D == 6.2);
                TestHelper.Assert(v.Str == "foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \u0007 \u0007");
                TestHelper.Assert(v.NoDefault == null);
                TestHelper.Assert(v.ZeroI == 0);
                TestHelper.Assert(v.ZeroL == 0);
                TestHelper.Assert(v.ZeroF == 0);
                TestHelper.Assert(v.ZeroDotF == 0);
                TestHelper.Assert(v.ZeroD == 0);
                TestHelper.Assert(v.ZeroDotD == 0);
            }

            {
                var v = new DerivedEx();
                TestHelper.Assert(!v.BoolFalse);
                TestHelper.Assert(v.BoolTrue);
                TestHelper.Assert(v.B == 1);
                TestHelper.Assert(v.S == 2);
                TestHelper.Assert(v.I == 3);
                TestHelper.Assert(v.L == 4);
                TestHelper.Assert(v.F == 5.1F);
                TestHelper.Assert(v.D == 6.2);
                TestHelper.Assert(v.Str == "foo \\ \"bar\n \r\n\t\u000b\f\u0007\b? \u0007 \u0007");
                TestHelper.Assert(v.NoDefault == null);
                TestHelper.Assert(v.C1 == Color.red);
                TestHelper.Assert(v.C2 == Color.green);
                TestHelper.Assert(v.C3 == Color.blue);
                TestHelper.Assert(v.Nc1 == Nested.Color.red);
                TestHelper.Assert(v.Nc2 == Nested.Color.green);
                TestHelper.Assert(v.Nc3 == Nested.Color.blue);
                TestHelper.Assert(v.ZeroI == 0);
                TestHelper.Assert(v.ZeroL == 0);
                TestHelper.Assert(v.ZeroF == 0);
                TestHelper.Assert(v.ZeroDotF == 0);
                TestHelper.Assert(v.ZeroD == 0);
                TestHelper.Assert(v.ZeroDotD == 0);
            }

            {
                var v = new ClassProperty();
                TestHelper.Assert(!v.BoolFalse);
                TestHelper.Assert(v.BoolTrue);
                TestHelper.Assert(v.B == 1);
                TestHelper.Assert(v.S == 2);
                TestHelper.Assert(v.I == 3);
                TestHelper.Assert(v.L == 4);
                TestHelper.Assert(v.F == 5.1F);
                TestHelper.Assert(v.D == 6.2);
                TestHelper.Assert(v.Str.Equals("foo bar"));
                TestHelper.Assert(v.NoDefault == null);
                TestHelper.Assert(v.ZeroI == 0);
                TestHelper.Assert(v.ZeroL == 0);
                TestHelper.Assert(v.ZeroF == 0);
                TestHelper.Assert(v.ZeroDotF == 0);
                TestHelper.Assert(v.ZeroD == 0);
                TestHelper.Assert(v.ZeroDotD == 0);
            }

            {
                var v = new ExceptionProperty();
                TestHelper.Assert(!v.BoolFalse);
                TestHelper.Assert(v.BoolTrue);
                TestHelper.Assert(v.B == 1);
                TestHelper.Assert(v.S == 2);
                TestHelper.Assert(v.I == 3);
                TestHelper.Assert(v.L == 4);
                TestHelper.Assert(v.F == 5.1F);
                TestHelper.Assert(v.D == 6.2);
                TestHelper.Assert(v.Str.Equals("foo bar"));
                TestHelper.Assert(v.NoDefault == null);
                TestHelper.Assert(v.ZeroI == 0);
                TestHelper.Assert(v.ZeroL == 0);
                TestHelper.Assert(v.ZeroF == 0);
                TestHelper.Assert(v.ZeroDotF == 0);
                TestHelper.Assert(v.ZeroD == 0);
                TestHelper.Assert(v.ZeroDotD == 0);
            }

            output.WriteLine("ok");
        }
 public decimal?Set(long?input,
                    ClassProperty property)
 {
     return(Convert.ToDecimal(input));
 }
 public string Get(int?input,
                   ClassProperty property)
 {
     return(input > 0 ? Convert.ToString(input) : null);
 }
示例#19
0
        private void AddClassProperty(CodeElements codeElements, ref List <ClassProperty> classProperties)
        {
            foreach (CodeElement2 codeElement in codeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementProperty)
                {
                    ClassProperty classProperty = new ClassProperty();
                    CodeProperty2 property      = codeElement as CodeProperty2;
                    classProperty.Name = property.Name;
                    //获取属性类型
                    var propertyType = property.Type;
                    switch (propertyType.TypeKind)
                    {
                    case vsCMTypeRef.vsCMTypeRefString:
                        classProperty.PropertyType = "string";
                        break;

                    case vsCMTypeRef.vsCMTypeRefInt:
                        classProperty.PropertyType = "int";
                        break;

                    case vsCMTypeRef.vsCMTypeRefLong:
                        classProperty.PropertyType = "long";
                        break;

                    case vsCMTypeRef.vsCMTypeRefByte:
                        classProperty.PropertyType = "byte";
                        break;

                    case vsCMTypeRef.vsCMTypeRefChar:
                        classProperty.PropertyType = "char";
                        break;

                    case vsCMTypeRef.vsCMTypeRefShort:
                        classProperty.PropertyType = "short";
                        break;

                    case vsCMTypeRef.vsCMTypeRefBool:
                        classProperty.PropertyType = "bool";
                        break;

                    case vsCMTypeRef.vsCMTypeRefDecimal:
                        classProperty.PropertyType = "decimal";
                        break;

                    case vsCMTypeRef.vsCMTypeRefFloat:
                        classProperty.PropertyType = "float";
                        break;

                    case vsCMTypeRef.vsCMTypeRefDouble:
                        classProperty.PropertyType = "double";
                        break;

                    default:
                        classProperty.PropertyType = propertyType.AsFullName;
                        break;
                    }

                    classProperties.Add(classProperty);
                }
            }
        }
示例#20
0
        /// <summary>
        /// 构造Entity数据
        /// </summary>
        private void InitModelData()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dataSource = entityModelBindingSource.List;

            fileModel.Name = textBox3.Text;
            fileModel.AngularEntityName = fileModel.Name.ToLower();
            fileModel.TableName         = textBox1.Text;
            fileModel.Description       = textBox4.Text;
            fileModel.ClassPropertys    = new List <ClassProperty>();
            fileModel.FirstLowerName    = FirstCharToLower(fileModel.Name);
            fileModel.HasDetail         = chkHasDetail.Checked;
            fileModel.DetailEntityName  = txtDetail.Text;
            fileModel.HasParent         = chkHasParent.Checked;
            fileModel.ParentEntityName  = txtParent.Text;

            enumEntities = new List <EnumEntity>();

            foreach (EntityModel model in dataSource)
            {
                var item     = DeepCopy(model);
                var property = new ClassProperty
                {
                    CnName          = item.Describe,
                    IsNull          = item.IsNull,
                    Name            = item.ColName,
                    Lenght          = item.DateType == "string" ? Convert.ToInt32(item.Length) : 0,
                    PropertyType    = item.DateType,
                    FirstLowerName  = FirstCharToLower(item.ColName),
                    IsCreateOrEdit  = item.IsCreateOrEdit,
                    IsFilter        = item.IsFilter,
                    IsRequired      = item.IsRequired,
                    IsShowInList    = item.IsShowInList,
                    ClassAttributes = new List <ClassProperty.ClassAttribute>()
                };
                fileModel.ClassPropertys.Add(property);

                if (item.DateType == "string")
                {
                    if (!string.IsNullOrEmpty(item.Length))
                    {
                        property.ClassAttributes.Add(new ClassProperty.ClassAttribute
                        {
                            NameValue = $"[MaxLength({item.Length})]"
                        });
                    }
                    else
                    {
                        throw new Exception("字符串类型必须指定长度");
                    }

                    if (!item.IsNull)
                    {
                        property.ClassAttributes.Add(new ClassProperty.ClassAttribute
                        {
                            NameValue = "[Required]"
                        });
                    }
                }
                else
                {
                    if (item.DateType == "decimal")
                    {
                        if (!string.IsNullOrEmpty(item.Length))
                        {
                            property.ClassAttributes.Add(new ClassProperty.ClassAttribute
                            {
                                NameValue = $"[Column(TypeName = \"decimal({item.Length})\")]"
                            });
                        }
                    }

                    if (item.DateType == "enum")
                    {
                        property.PropertyType = item.EnumName;

                        var enumEntity = new EnumEntity
                        {
                            EnumName  = item.EnumName,
                            EnumDes   = item.Describe,
                            NameSpace = fileModel.Namespace + fileModel.DirName,
                            Values    = new List <EnumValue>()
                        };

                        enumEntities.Add(enumEntity);
                        var values = item.EnumValue.Split(',');
                        foreach (var value in values)
                        {
                            if (value.Contains(":"))
                            {
                                var names = value.Split(':');
                                enumEntity.Values.Add(new Models.TemplateModels.EnumValue {
                                    EnumValueName = names[0], Value = Convert.ToInt32(names[1])
                                });
                            }
                            else
                            {
                                enumEntity.Values.Add(new Models.TemplateModels.EnumValue {
                                    EnumValueName = value
                                });
                            }
                        }
                    }

                    if (item.IsNull)
                    {
                        property.PropertyType += "?";
                    }
                }
            }

            fileModel.Parameters       = string.Join(", ", fileModel.ClassPropertys.OrderBy(o => o.PropertyType).Select(s => $"{s.PropertyType} {s.FirstLowerName}"));
            fileModel.MethodParameters = string.Join(", ", fileModel.ClassPropertys.OrderBy(o => o.PropertyType).Select(s => s.FirstLowerName));
            fileModel.CreateParameters = string.Join(", ", fileModel.ClassPropertys.OrderBy(o => o.PropertyType).Select(s => $"dto.{s.Name}"));
        }
示例#21
0
 public bool Compare(ClassProperty other, bool verbose)
 {
     var result = SomeString == other.SomeString;
     result &= SomeInt == other.SomeInt;
     if (verbose)
     {
         Console.WriteLine("  SomeString:");
         Console.WriteLine("  Me: {0}, Them: {1}", SomeString, other.SomeString);
         Console.WriteLine("  SomeInt:");
         Console.WriteLine("  Me: {0}, Them: {1}", SomeInt, other.SomeInt);
     }
     return result;
 }
 public Guid Get(string input, ClassProperty property)
 {
     Guid.TryParse(input, out Guid output);
     return(output);
 }
 public string Set(Guid input, ClassProperty property)
 {
     return(input.ToString());
 }
示例#24
0
 public WithHandlerEnum?Get(decimal?input, ClassProperty property)
 => throw new NotImplementedException();
示例#25
0
        private static void EmitDataReaderToDataEntityMapping <TEntity>(ILGenerator ilGenerator, int ordinal, ClassProperty property, FieldDefinition fieldDefinition)
            where TEntity : class
        {
            // Get the property type
            var isNullable     = fieldDefinition == null || fieldDefinition?.IsNullable == true;
            var underlyingType = Nullable.GetUnderlyingType(property.PropertyInfo.PropertyType);
            var propertyType   = underlyingType ?? property.PropertyInfo.PropertyType;

            // Variables for ending this property emitting
            var endLabel = ilGenerator.DefineLabel();

            // Load the data DataReader instance from argument 0
            ilGenerator.Emit(OpCodes.Ldarg, 0);

            // Load the value base on the ordinal
            ilGenerator.Emit(OpCodes.Ldc_I4, ordinal);
            ilGenerator.Emit(OpCodes.Callvirt, typeof(DbDataReader).GetTypeInfo().GetMethod("get_Item", new[] { typeof(int) }));
            ilGenerator.Emit(OpCodes.Stloc, 1);

            // Check if nullable in the actual definition
            if (isNullable == true)
            {
                // Load the resulted Value and DBNull.Value for comparisson
                ilGenerator.Emit(OpCodes.Ldloc, 1);
                ilGenerator.Emit(OpCodes.Ldsfld, typeof(DBNull).GetTypeInfo().GetField("Value"));
                ilGenerator.Emit(OpCodes.Ceq);
                ilGenerator.Emit(OpCodes.Brtrue_S, endLabel);
            }

            // Load the DataEntity instance
            ilGenerator.Emit(OpCodes.Ldloc, 0);
            ilGenerator.Emit(OpCodes.Ldloc, 1);

            // Switch which method of Convert are going to used
            if (propertyType != typeof(byte[]))
            {
                // Get the proper convert method
                var convertMethod = typeof(Convert).GetTypeInfo().GetMethod($"To{propertyType.Name}", new[] { typeof(object) }) ??
                                    typeof(Convert).GetTypeInfo().GetMethod($"ToString", new[] { typeof(object) });

                // Convert the value
                ilGenerator.Emit(OpCodes.Call, convertMethod);

                // Parse if it is Guid
                var parseMethod = (MethodInfo)null;

                // Switch to the correct parser method
                if (propertyType == typeof(Guid) ||
                    propertyType == typeof(DateTimeOffset) ||
                    propertyType == typeof(TimeSpan))
                {
                    parseMethod = propertyType.GetTypeInfo().GetMethod("Parse", new[] { typeof(string) });
                }

                // Do the parse if set
                if (parseMethod != null)
                {
                    ilGenerator.Emit(OpCodes.Call, parseMethod);
                }
            }

            // Check for nullable based on the underlying type
            if (underlyingType != null)
            {
                // Get the type of Nullable<T> object
                var nullableType = typeof(Nullable <>).MakeGenericType(propertyType);

                // Create a new instance of Nullable<T> object
                ilGenerator.Emit(OpCodes.Newobj, nullableType.GetTypeInfo().GetConstructor(new[] { propertyType }));
            }

            // Call the (Property.Set) or (Property = Value)
            ilGenerator.Emit(OpCodes.Call, property.PropertyInfo.GetSetMethod());

            // End label for DBNull.Value checking
            ilGenerator.MarkLabel(endLabel);
        }
 public object Set(long?input,
                   ClassProperty property)
 {
     return(input);
 }
示例#27
0
 public NormalTableInsideInlineTable()
 {
     this.InlineL2 = new ClassProperty();
 }
示例#28
0
 public CallbackTuple(IVisualElement element, IClassMethod <TProp> vmMethod)
 {
     this.element  = element;
     this.vmMethod = vmMethod;
     vmProperty    = null;
 }
 public int?Set(string input,
                ClassProperty property)
 {
     return(Convert.ToInt32(input));
 }
示例#30
0
        /// <summary>
        /// Create Parameter, the process will handle value conversion and type conversion.
        /// </summary>
        /// <param name="command">The command object to be used.</param>
        /// <param name="name">Entity property's name.</param>
        /// <param name="value">Entity property's value, maybe null.</param>
        /// <param name="classProperty">
        /// The entity's class property information. <br />
        /// If the parameter is a dictionary, it will be null, otherwise it will not be null.
        /// </param>
        /// <param name="dbField">
        /// Used to get the actual field type information of the database to determine whether automatic type conversion is required. <br />
        /// When the tableName is assigned, it will be based on the database field information obtained by the tableName, so this parameter will be null in most cases.
        /// </param>
        /// <param name="parameterDirection">The direction of the parameter.</param>
        /// <param name="fallbackType">Used when none of the above parameters can determine the value of Parameter.DbType.</param>
        /// <returns>An instance of the newly created parameter object.</returns>
        private static IDbDataParameter CreateParameter(IDbCommand command,
                                                        string name,
                                                        object value,
                                                        ClassProperty classProperty,
                                                        DbField dbField,
                                                        ParameterDirection?parameterDirection,
                                                        Type fallbackType)
        {
            /*
             * In some cases, the value type and the classProperty type will be inconsistent, Therefore, the type gives priority to value.
             * ex: in RepoDb.MySql.IntegrationTests.TestMySqlConnectionForQueryForMySqlMapAttribute
             *    entity AttributeTable.Id = int
             *    database completetable.Id = bigint(20) AUTO_INCREMENT
             *    value id in connection.Query<AttributeTable>(id) is from connection.Insert<AttributeTable>(table) = ulong
             */
            var valueType = (value?.GetType() ?? classProperty?.PropertyInfo.PropertyType).GetUnderlyingType();

            /*
             * Try to get the propertyHandler, the order of the source of resolve is classProperty and valueType.
             * If the propertyHandler exists, the value and DbType are re-determined by the propertyHandler.
             */
            var propertyHandler =
                classProperty?.GetPropertyHandler() ??
                (valueType == null ? null : PropertyHandlerCache.Get <object>(valueType));

            if (propertyHandler != null)
            {
                var propertyHandlerSetMethod = propertyHandler.GetType().GetMethod("Set");
                value     = propertyHandlerSetMethod.Invoke(propertyHandler, new[] { value, classProperty });
                valueType = propertyHandlerSetMethod.ReturnType.GetUnderlyingType();
            }

            /*
             * When the database field information exists and the field type definition is found to be different from the valueType,
             * if automatic type conversion is activated at this time, it will be processed.
             */
            if (valueType != null && dbField != null && IsAutomaticConversion(dbField))
            {
                var dbFieldType = dbField.Type.GetUnderlyingType();
                if (dbFieldType != valueType)
                {
                    if (value != null)
                    {
                        value = AutomaticConvert(value, valueType, dbFieldType);
                    }
                    valueType = dbFieldType;
                }
            }

            /*
             * Set DbType as much as possible, to avoid parameter misjudgment when Value is null.
             * order:
             *      1. attribute level, TypeMapAttribute define on class's property
             *      2. property level, assigned by TypeMapper.Add(entityType, property, dbType, ...)
             *      3. type level, use TypeMapCache, assigned by TypeMapper.Add(type, dbType, ...), not included Primitive mapping.
             *      4. type level, primitive mapping, included special type. ex: byte[] ...etc.
             *      5. if isEnum, use Converter.EnumDefaultDatabaseType.
             */

            // if classProperty exists, try get dbType from attribute level or property level,
            // The reason for not using classProperty.GetDbType() is to avoid getting the type level mapping.
            var dbType = classProperty?.GetDbType();

            if (dbType == null && (valueType ??= dbField?.Type.GetUnderlyingType() ?? fallbackType) != null)
            {
                dbType =
                    valueType.GetDbType() ??                                        // type level, use TypeMapCache
                    clientTypeToDbTypeResolver.Resolve(valueType) ??                // type level, primitive mapping
                    (dbField?.Type != null ?
                     clientTypeToDbTypeResolver.Resolve(dbField?.Type) : null);     // fallback to the database type
            }
            if (dbType == null && valueType.IsEnum)
            {
                dbType = Converter.EnumDefaultDatabaseType;                         // use Converter.EnumDefaultDatabaseType
            }

            /*
             * Return the parameter
             */
            return(command.CreateParameter(name, value, dbType, parameterDirection));
        }
示例#31
0
 public decimal?Set(WithHandlerEnum?input, ClassProperty property)
 => input switch
 {
示例#32
0
 public InlineTableWithDisallowedNormalTable()
 {
     this.Disallowed = new ClassProperty();
 }
 public string Set(TargetModel input,
                   ClassProperty property)
 {
     return(input?.Value);
 }
示例#34
0
 public CallbackTuple(IVisualElement element, ClassProperty <TProp> vmProperty)
 {
     this.element    = element;
     this.vmProperty = vmProperty;
     vmMethod        = null;
 }