Exemplo n.º 1
0
        public void GetValidationsForPropertyTest()
        {
            var p           = PropertyUnity.GetProperty(typeof(Products), "ProductName");
            var validations = ValidationUnity.GetValidations(p);

            Console.WriteLine(validations.Count());
        }
Exemplo n.º 2
0
        /// <summary>
        /// 执行Batch-Insert后更新主键到实体集。
        /// </summary>
        /// <param name="rows">Update影响的行数。</param>
        /// <param name="table"></param>
        /// <param name="entities"></param>
        /// <returns></returns>
        private static int UpdateEntities(int rows, DataTable table, IEnumerable entities)
        {
            var       index      = 0;
            IProperty pkProperty = null;

            foreach (IEntity entity in entities)
            {
                if (pkProperty == null)
                {
                    pkProperty = PropertyUnity.GetPrimaryProperties(entity.EntityType)
                                 .FirstOrDefault(s => s.Info.GenerateType == IdentityGenerateType.AutoIncrement);
                }

                if (pkProperty == null)
                {
                    return(rows);
                }

                var row     = table.Rows[index++];
                var pkValue = PropertyValue.NewValue(row.ItemArray[table.Columns.Count - 1], pkProperty.Type);
                entity.InitializeValue(pkProperty, pkValue);
            }

            return(rows);
        }
Exemplo n.º 3
0
        public void Bind(Type modelType, string propertyName, ISettingsBindable settings)
        {
            var nsettings = settings as NumberBoxSettings;

            if (!typeof(IEntity).IsAssignableFrom(modelType))
            {
                return;
            }

            //获取对应的依赖属性
            var property = PropertyUnity.GetProperty(modelType, propertyName);

            if (property == null)
            {
                return;
            }

            nsettings.Precision = property.Info.Scale;

            //找 RangeAttribute 特性
            var range = ValidationUnity.GetValidations(property).Where(s => s is RangeAttribute).Cast <RangeAttribute>().FirstOrDefault();

            if (range != null)
            {
                nsettings.Min = range.Minimum.To <decimal?>();
                nsettings.Max = range.Maximum.To <decimal?>();
            }
        }
Exemplo n.º 4
0
        private static LambdaExpression BindPrimaryExpression(IEntity entity)
        {
            var primaryProperties = PropertyUnity.GetPrimaryProperties(entity.EntityType).ToList();

            if (primaryProperties.IsNullOrEmpty())
            {
                return(null);
            }

            var expressions = new List <Expression>();
            var parExp      = Expression.Parameter(entity.EntityType, "s");

            foreach (var property in primaryProperties)
            {
                var value = entity.GetValue(property);
                if (PropertyValue.IsEmpty(value))
                {
                    continue;
                }

                var getValExp = BindGetValueExpression(property, value);
                if (getValExp == null)
                {
                    continue;
                }

                var equalExp = Expression.MakeMemberAccess(parExp, property.Info.ReflectionInfo).Equal(getValExp);

                expressions.Add(equalExp);
            }

            var predicate = expressions.Aggregate(Expression.And);

            return(Expression.Lambda(predicate, parExp));
        }
Exemplo n.º 5
0
        /// <summary>
        /// 获取指定属性名称的 <see cref="ValidationAttribute"/> 定义集。
        /// </summary>
        /// <param name="entityType">一个实体的类型。</param>
        /// <returns></returns>
        private static Dictionary<string, List<ValidationAttribute>> GetPropertyValidations(Type entityType)
        {
            var dictionary = new Dictionary<string, List<ValidationAttribute>>();
            var metadataType = entityType.GetCustomAttributes<MetadataTypeAttribute>(true).FirstOrDefault();
            if (metadataType != null &&
                typeof(IMetadataContainer).IsAssignableFrom(metadataType.MetadataClassType))
            {
                return metadataType.MetadataClassType.New<IMetadataContainer>().InitializeRules();
            }

            var properties = metadataType == null ? 
                PropertyUnity.GetProperties(entityType).Select(s => s.Info.ReflectionInfo) : 
                metadataType.MetadataClassType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                var attributes = property.GetCustomAttributes<ValidationAttribute>().ToList();
                if (attributes.Count == 0)
                {
                    continue;
                }

                IProperty dp;
                if ((dp = CheckPropertyValid(entityType, property)) == null)
                {
                    continue;
                }

                var list = dictionary.TryGetValue(property.Name, () => new List<ValidationAttribute>());
                MarkValidationProperty(dp, attributes);
                list.AddRange(attributes);
            }

            return dictionary;
        }
Exemplo n.º 6
0
        public void Bind(Type modelType, string propertyName, ISettingsBindable settings)
        {
            //模型类型必须实现自 IEntity
            if (!typeof(IEntity).IsAssignableFrom(modelType))
            {
                return;
            }

            //获取对应的依赖属性
            var property = PropertyUnity.GetProperty(modelType, propertyName);

            if (property == null)
            {
                return;
            }

            var vsettings = settings as ValidateBoxSettings;
            //获取依赖属性所指定的验证特性
            var validTypes = vsettings.ValidType == null ? new List <string>() :
                             new List <string>(vsettings.ValidType);

            foreach (var validation in ValidationUnity.GetValidations(property))
            {
                ParseValidation(vsettings, validation, validTypes);
            }

            vsettings.ValidType = validTypes.ToArray();
        }
Exemplo n.º 7
0
        /// <summary>
        /// 构造所有字段的查询表达式。
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private static LambdaExpression BindAllFieldExpression(IEntity entity)
        {
            var expressions = new List <Expression>();
            var parExp      = Expression.Parameter(entity.EntityType, "s");

            foreach (var property in PropertyUnity.GetPersistentProperties(entity.EntityType))
            {
                var oldValue = entity.GetOldValue(property);
                if (PropertyValue.IsEmpty(oldValue))
                {
                    continue;
                }

                var getValExp = BindGetValueExpression(property, oldValue);
                if (getValExp == null)
                {
                    continue;
                }

                var equalExp = Expression.MakeMemberAccess(parExp, property.Info.ReflectionInfo)
                               .Equal(getValExp);

                expressions.Add(equalExp);
            }

            var predicate = expressions.Aggregate(Expression.And);

            return(Expression.Lambda(predicate, parExp));
        }
        /// <summary>
        /// 尝试添加新的字段。
        /// </summary>
        /// <param name="database">提供给当前插件的 <see cref="IDatabase"/> 对象。</param>
        /// <param name="metadata">实体元数据。</param>
        /// <param name="tableName">数据表名称。</param>
        public IList <IProperty> TryAddFields(IDatabase database, EntityMetadata metadata, string tableName)
        {
            var schema = database.Provider.GetService <ISchemaProvider>();
            var syntax = database.Provider.GetService <ISyntaxProvider>();

            if (schema == null || syntax == null)
            {
                return(null);
            }

            //查询目前数据表中的所有字段
            var columns = schema.GetSchemas <Column>(database, s => s.TableName == tableName).Select(s => s.Name).ToArray();

            //筛选出新的字段
            var properties = PropertyUnity.GetPersistentProperties(metadata.EntityType)
                             .Where(s => !columns.Contains(s.Info.FieldName, StringComparer.CurrentCultureIgnoreCase)).ToList();

            if (properties.Count != 0)
            {
                var commands = BuildAddFieldCommands(syntax, tableName, properties);
                BatchExecuteAsync(database, commands);
            }

            return(properties);
        }
Exemplo n.º 9
0
        public void TestDynamic()
        {
            var builder = new EntityTypeBuilder("test");

            builder.Properties.Add(new GeneralProperty()
            {
                Name = "aa", Type = typeof(string), Info = new PropertyMapInfo {
                    FieldName = "aa", IsPrimaryKey = true, DefaultValue = PropertyValue.NewValue(33, typeof(int)), GenerateType = IdentityGenerateType.AutoIncrement
                }
            });
            builder.Properties.Add(new GeneralProperty()
            {
                Name = "bb", Type = typeof(string), Info = new PropertyMapInfo {
                    FieldName = "bb", IsNullable = true
                }
            });
            builder.Properties.Add(new GeneralProperty()
            {
                Name = "cc", Type = typeof(int), Info = new PropertyMapInfo {
                    FieldName = "cc", Scale = 2
                }
            });
            builder.Properties.Add(new EntityProperty()
            {
                Name = "dd", Type = typeof(Products)
            });
            var a = builder.Create();

            var pp = PropertyUnity.GetPrimaryProperties(a).FirstOrDefault(s => s.Info.GenerateType == IdentityGenerateType.AutoIncrement);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取指定类型的实体元数据。
        /// </summary>
        /// <param name="entityType">实体类型。</param>
        /// <returns></returns>
        public static EntityMetadata GetEntityMetadata(Type entityType)
        {
            Guard.ArgumentNull(entityType, nameof(entityType));

            entityType = entityType.GetDefinitionEntityType();

            return(cache.GetOrAdd(entityType, () =>
            {
                var metadata = new EntityMetadata(entityType);

                //由于此代码段是缓存项创建工厂函数,此时的 metadata 并未添加到缓存中,接下来 PropertyUnity
                //会再一次获取 EntityMetadata,因此需要在此线程中共享出 EntityMetadata
                using (var scope = new MetadataScope {
                    Metadata = metadata
                })
                {
                    if (typeof(ICompilableEntity).IsAssignableFrom(entityType))
                    {
                        PropertyUnity.Initialize(entityType);
                    }
                    else
                    {
                        //需要找出其中的一个字段,然后以引发 RegisterProperty 调用
                        var field = entityType.GetFields(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public).FirstOrDefault();
                        if (field != null)
                        {
                            field.GetValue(null);
                        }
                    }
                }

                return metadata;
            }));
        }
Exemplo n.º 11
0
        private static List <Type> AnalysisType(Type type)
        {
            var types = new List <Type>();

            if (type.IsGenericType)
            {
                type.GetGenericArguments().ForEach(s => types.AddRange(AnalysisType(s)));
            }
            else if (type.IsArray)
            {
                types.AddRange(AnalysisType(type.GetElementType()));
            }
            else if (typeof(IEntity).IsAssignableFrom(type))
            {
                types.Add(type);

                foreach (var property in PropertyUnity.GetRelatedProperties(type))
                {
                    if (property is EntityProperty)
                    {
                        types.Add(property.Type);
                    }
                }
            }

            return(types);
        }
Exemplo n.º 12
0
        private static LambdaExpression BindPrimaryExpression(IEntity entity)
        {
            var primaryProperties = PropertyUnity.GetPrimaryProperties(entity.EntityType).ToList();

            if (primaryProperties.IsNullOrEmpty())
            {
                return(null);
            }

            var        parExp     = Expression.Parameter(entity.EntityType, "s");
            Expression expression = null;

            foreach (var p in primaryProperties)
            {
                var kv        = entity.InternalGetValue(p);
                var condition = Expression.MakeMemberAccess(parExp, p.Info.ReflectionInfo).Equal(Expression.Convert(Expression.Constant(kv), p.Type));
                if (expression == null)
                {
                    expression = condition;
                }
                else
                {
                    expression = Expression.And(expression, condition);
                }
            }

            return(Expression.Lambda(expression, parExp));
        }
Exemplo n.º 13
0
        protected override Expression VisitMember(MemberExpression m)
        {
            var       source = Visit(m.Expression);
            IProperty property;

            // **fix** 解决无法返回两级以上关联对象的问题
            // var ex = source as EntityExpression
            // if (ex != null &&
            if ((property = PropertyUnity.GetProperty(m.Expression.Type, m.Member.Name)) != null &&
                property is RelationProperty)
            {
                var projection = (ProjectionExpression)Visit(QueryUtility.GetMemberExpression(_transContext, source, property));
                if (_currentFrom != null && m.Member.GetMemberType().GetEnumerableType() == null)
                {
                    // convert singleton associations directly to OUTER APPLY
                    projection = projection.AddOuterJoinTest();
                    var newFrom = new JoinExpression(JoinType.OuterApply, _currentFrom, projection.Select, null);
                    _currentFrom = newFrom;
                    return(projection.Projector);
                }

                return(projection);
            }

            var result = QueryBinder.BindMember(source, m.Member);

            if (result is MemberExpression mex &&
                mex.Member == m.Member &&
                mex.Expression == m.Expression)
            {
                return(m);
            }

            return(result);
        }
Exemplo n.º 14
0
 /// <summary>
 /// 加载实体类型中的所有属性。
 /// </summary>
 private void LoadProperties()
 {
     foreach (var property in PropertyUnity.GetPersistentProperties(entityType))
     {
         var item = new ListViewItem(property.Name);
         Items.Add(item);
     }
 }
Exemplo n.º 15
0
        public void TestGetProperty1()
        {
            var pp = PropertyUnity.GetProperty(typeof(PA1), "Name");

            Assert.IsNull(pp);
            pp = PropertyUnity.GetProperty(typeof(PA2), "Name");
            Assert.IsNotNull(pp);
        }
Exemplo n.º 16
0
        protected Expression Compare(BinaryExpression bop)
        {
            var e1 = this.SkipConvert(bop.Left);
            var e2 = this.SkipConvert(bop.Right);
            EntityExpression entity1 = e1 as EntityExpression;
            EntityExpression entity2 = e2 as EntityExpression;

            if (entity1 == null && e1 is OuterJoinedExpression)
            {
                entity1 = ((OuterJoinedExpression)e1).Expression as EntityExpression;
            }

            if (entity2 == null && e2 is OuterJoinedExpression)
            {
                entity2 = ((OuterJoinedExpression)e2).Expression as EntityExpression;
            }

            bool negate = bop.NodeType == ExpressionType.NotEqual;

            if (entity1 != null)
            {
                return(this.MakePredicate(e1, e2, PropertyUnity.GetPrimaryProperties(entity1.Metadata.EntityType).Select(s => (MemberInfo)s.Info.ReflectionInfo), negate));
            }
            else if (entity2 != null)
            {
                return(this.MakePredicate(e1, e2, PropertyUnity.GetPrimaryProperties(entity2.Metadata.EntityType).Select(s => (MemberInfo)s.Info.ReflectionInfo), negate));
            }

            var dm1 = this.GetDefinedMembers(e1);
            var dm2 = this.GetDefinedMembers(e2);

            if (dm1 == null && dm2 == null)
            {
                // neither are constructed types
                return(bop);
            }

            if (dm1 != null && dm2 != null)
            {
                // both are constructed types, so they'd better have the same members declared
                HashSet <string> names1 = new HashSet <string>(dm1.Select(m => m.Name), StringComparer.Ordinal);
                HashSet <string> names2 = new HashSet <string>(dm2.Select(m => m.Name), StringComparer.Ordinal);
                if (names1.IsSubsetOf(names2) && names2.IsSubsetOf(names1))
                {
                    return(MakePredicate(e1, e2, dm1, negate));
                }
            }
            else if (dm1 != null)
            {
                return(MakePredicate(e1, e2, dm1, negate));
            }
            else if (dm2 != null)
            {
                return(MakePredicate(e1, e2, dm2, negate));
            }

            throw new InvalidOperationException("");
        }
Exemplo n.º 17
0
        protected override Expression VisitEntity(EntityExpression entity)
        {
            var mbmInitExp = entity.Expression as MemberInitExpression;

            var properties = new List <Expression>();
            var values     = new List <Expression>();
            var bindings   = new List <MemberBinding>();

            mbmInitExp.Bindings.ForEach(s =>
            {
                if (s is MemberAssignment assign)
                {
                    var expression = Visit(assign.Expression);
                    if (entity.IsNoTracking)
                    {
                        bindings.Add(Expression.Bind(assign.Member, expression));
                    }
                    else
                    {
                        var proprety = PropertyUnity.GetProperty(mbmInitExp.Type, assign.Member.Name);
                        properties.Add(Expression.Constant(proprety));

                        if (PropertyValue.IsSupportedType(proprety.Type))
                        {
                            if (expression.Type.GetNonNullableType().IsEnum)
                            {
                                expression = Expression.Convert(expression, typeof(Enum));
                            }

                            var pValue = Expression.Convert(expression, typeof(PropertyValue));
                            values.Add(pValue);
                        }
                        else
                        {
                            var pValue = Expression.Call(null, MthNewPropertyValue, expression, Expression.Constant(null, typeof(Type)));
                            values.Add(pValue);
                        }
                    }
                }
            });

            if (entity.IsNoTracking)
            {
                return(Expression.MemberInit(mbmInitExp.NewExpression, bindings));
            }

            var e = TranslateScope.Current.ContextService as IEntityPersistentEnvironment;
            var c = TranslateScope.Current.ContextService as IEntityPersistentInstanceContainer;

            var constCall = Expression.Call(null, MthConstruct,
                                            Visit(mbmInitExp.NewExpression),
                                            Expression.NewArrayInit(typeof(IProperty), properties.ToArray()),
                                            Expression.NewArrayInit(typeof(PropertyValue), values.ToArray()),
                                            Expression.Constant(c, typeof(IEntityPersistentInstanceContainer)),
                                            Expression.Constant(e, typeof(IEntityPersistentEnvironment)));

            return(Expression.Convert(constCall, entity.Type));
        }
Exemplo n.º 18
0
        public void GetPropertyValidationsTest()
        {
            var p = PropertyUnity.GetProperty(typeof(Orders), "CustomerID");

            ValidationUnity.RegisterValidation(p, new ProductQuantityValidateAttribute());
            var validations = ValidationUnity.GetValidations(p);

            Console.WriteLine(validations.Count());
        }
Exemplo n.º 19
0
 private static IEnumerable <ColumnAssignment> GetUpdateArguments(TableExpression table, IEnumerable <MemberAssignment> bindings)
 {
     return(from m in bindings
            let property = PropertyUnity.GetProperty(table.Type, m.Member.Name)
                           select new ColumnAssignment(
                (ColumnExpression)GetMemberExpression(table, property),
                m.Expression
                ));
 }
        void IEntityContextPreInitializer.PreInitialize(EntityContextPreInitializeContext context)
        {
            foreach (var map in context.Mappers)
            {
                if (_entityTypes != null && _entityTypes.Count != 0 && !_entityTypes.Contains(map.EntityType))
                {
                    continue;
                }

                var pk = PropertyUnity.GetPrimaryProperties(map.EntityType).FirstOrDefault(s => s.Info.GenerateType != IdentityGenerateType.None);
                if (pk == null)
                {
                    continue;
                }

                var database   = context.EntityContext.Database;
                var metadata   = EntityMetadataUnity.GetEntityMetadata(map.EntityType);
                var tableName  = metadata.TableName.ToUpper();
                var columnName = pk.Info.FieldName.ToUpper();

                var sequenceName = FixSequenceName(tableName, columnName);

                //创建序列
                SqlCommand sql    = $"SELECT 1 FROM USER_SEQUENCES WHERE SEQUENCE_NAME = '{sequenceName}'";
                var        result = database.ExecuteScalar(sql);

                //不存在的话先创建序列
                if (result == DBNull.Value || result == null)
                {
                    //取表中该列的最大值 + 1
                    sql = $"SELECT MAX({columnName}) FROM {tableName}";
                    var value = database.ExecuteScalar <int>(sql) + 1;

                    sql = @"CREATE SEQUENCE {sequenceName} START WITH {value}";
                    database.ExecuteNonQuery(sql);
                }

                //创建触发器
                sql    = $"SELECT 1 FROM ALL_TRIGGERS WHERE TRIGGER_NAME = 'TRIG_{tableName}'";
                result = database.ExecuteScalar(sql);

                //不存在的话先创建序列
                if (result == DBNull.Value || result == null)
                {
                    sql = $@"
CREATE OR REPLACE TRIGGER TRIG_{tableName}
BEFORE INSERT ON {tableName} FOR EACH ROW WHEN (NEW.{columnName} IS NULL OR NEW.{columnName} = 0)
BEGIN
SELECT {sequenceName}.NEXTVAL INTO:NEW.{columnName} FROM DUAL;
END;";

                    database.ExecuteNonQuery(sql);
                }

                pk.Info.GenerateType = IdentityGenerateType.None;
            }
        }
Exemplo n.º 21
0
 public void GetValidationsForPropertyParallelTest()
 {
     Parallel.For(0, 100, (i) =>
     {
         var p           = PropertyUnity.GetProperty(typeof(Products), "ProductName");
         var validations = ValidationUnity.GetValidations(p);
         Console.WriteLine(validations.Count());
     });
 }
Exemplo n.º 22
0
        public void TestGetProperty()
        {
            var customer  = Customers.New();
            var property1 = PropertyUnity.GetProperty(customer.GetType(), "CustomerID");
            var property2 = PropertyUnity.GetProperty(typeof(Customers), "CustomerID");

            Assert.IsNotNull(property1);
            Assert.IsNotNull(property2);
            Assert.AreEqual(property1, property2);
        }
Exemplo n.º 23
0
        private static List <IProperty> GetUpdateProperties(IEntity entity)
        {
            var properties = PropertyUnity.GetProperties(entity.EntityType, true);
            var entityEx   = entity as IEntityStatefulExtension;

            return((from property in properties
                    where (entityEx != null && entityEx.IsModified(property.Name)) &&
                    property is ISavedProperty
                    select property).ToList());
        }
Exemplo n.º 24
0
 /// <summary>
 /// 检查实体的关联属性。
 /// </summary>
 /// <param name="entity"></param>
 private void HandleRelationProperties(IEntity entity)
 {
     entity.As <IEntityStatefulExtension>(ext =>
     {
         var properties = PropertyUnity.GetRelatedProperties(entity.EntityType).Where(s => ext.IsModified(s.Name)).ToList();
         if (properties.Count > 0)
         {
             HandleRelationProperties(entity, properties);
         }
     });
 }
Exemplo n.º 25
0
        /// <summary>
        /// 检查有没有关联属性被修改.
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private bool CheckRelationHasModified(IEntity entity)
        {
            var modified = false;

            entity.As <IEntityStatefulExtension>(ext =>
            {
                modified = PropertyUnity.GetRelatedProperties(entity.EntityType).Any(s => ext.IsModified(s.Name));
            });

            return(modified);
        }
Exemplo n.º 26
0
        public void ValidateWithCustomAttributeTest1()
        {
            var p = PropertyUnity.GetProperty(typeof(Orders), "CustomerID");

            ValidationUnity.RegisterValidation(p, new AnyValidateAttribute());
            var o = new Orders {
                CustomerID = "AA"
            };

            ValidationUnity.Validate(o);
        }
Exemplo n.º 27
0
        public void RegisterPropertyByLinqTest()
        {
            var property = PropertyUnity.RegisterProperty <Company>(s => s.Name, new PropertyMapInfo
            {
                FieldName   = "Name",
                Length      = 20,
                Description = "公司名称",
            });

            Assert.IsNotNull(property);
        }
Exemplo n.º 28
0
        public void RegisterPropertyTest()
        {
            var property = PropertyUnity.RegisterProperty("Name", typeof(string), typeof(Company), new PropertyMapInfo
            {
                FieldName   = "Name",
                Length      = 20,
                Description = "公司名称",
            });

            Assert.IsNotNull(property);
        }
Exemplo n.º 29
0
            protected override Expression VisitMember(MemberExpression node)
            {
                var property = PropertyUnity.GetProperty(node.Member.DeclaringType, node.Member.Name);

                if (property != null)
                {
                    var column = _columns.FirstOrDefault(s => s.Name == node.Member.Name);
                    return(column != null ? column.Expression : node);
                }

                return(node);
            }
Exemplo n.º 30
0
        private static List <IProperty> GetInsertProperties(IEntity entity)
        {
            var properties = PropertyUnity.GetProperties(entity.EntityType, true);
            var entityEx   = entity as IEntityStatefulExtension;

            return((from property in properties
                    where property is ISavedProperty
                    where (entityEx != null && entityEx.IsModified(property.Name)) ||
                    !property.Info.DefaultValue.IsNullOrEmpty() ||
                    property.Info.GenerateType == IdentityGenerateType.Generator
                    select property).ToList());
        }