Esempio n. 1
0
 public int Update(TEntity entity)
 {
     lock (OBJLOCK)
     {
         VerifyExtension.Verity(entity);
         RemoveHoldingEntityInContext(entity);
         dbcontext.Set <TEntity>().Attach(entity);
         PropertyInfo[] props = entity.GetType().GetProperties();
         foreach (PropertyInfo prop in props)
         {
             Object[]           attrs     = prop.GetCustomAttributes(true);
             string             strDesc   = string.Empty;
             NotMappedAttribute notMapped = Attribute.GetCustomAttribute(prop, typeof(NotMappedAttribute)) as NotMappedAttribute;
             if (notMapped == null)
             {
                 if (prop.GetValue(entity, null) != null)
                 {
                     if (prop.GetValue(entity, null).ToString() == "&nbsp;")
                     {
                         dbcontext.Entry(entity).Property(prop.Name).CurrentValue = null;
                     }
                     dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
                 }
             }
         }
         return(dbcontext.SaveChanges());
     }
 }
Esempio n. 2
0
        public void MyTableFieldsCopy <T, U>(T edtCtx, U oldRow, IDictionary <string, object> newValue)
        {
            // edtCtx::EditFormContext (oldRow disinda baska alanlar da var)
            // oldRow::??model bunun uzerinden git
            foreach (var fld in oldRow.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty))
            {
                NotMappedAttribute nma = (NotMappedAttribute)fld.GetCustomAttribute(typeof(NotMappedAttribute));

                //if (fld.Name != "SelectedTGs") // SelectedTGs Table da yok: NotMapped olarak isaretlendi
                if (nma == null)
                {
                    if (fld.CanWrite)
                    {
                        var newVal = edtCtx.GetType().GetProperty(fld.Name)?.GetValue(edtCtx);
                        var oldVal = oldRow.GetType().GetProperty(fld.Name)?.GetValue(oldRow);

                        if (!object.Equals(newVal, oldVal))
                        {
                            newValue.Add(fld.Name, newVal);
                            //oldRow.GetType().GetProperty(fld.Name)?.SetValue(oldRow, newVal); // Gerek yok, cagiran yapiyor
                        }
                    }
                }
            }
        }
Esempio n. 3
0
        public static IEnumerable <AtomPropertyInfo> GetEntityProperties(this Type type, bool keyOnly = false)
        {
            ThreadSafeDictionary <Type, IEnumerable <AtomPropertyInfo> > cache = keyOnly ? _keyList : _allList;


            return(cache.GetOrAdd(type, t =>
            {
                List <AtomPropertyInfo> list = new List <AtomPropertyInfo>();

                foreach (PropertyInfo p in type.GetCachedProperties())
                {
                    KeyAttribute a = p.GetCustomAttribute <KeyAttribute>();
                    if (a == null)
                    {
                        continue;
                    }
                    NotMappedAttribute notMapped = p.GetCustomAttribute <NotMappedAttribute>();
                    if (notMapped != null)
                    {
                        continue;
                    }
                    if (keyOnly)
                    {
                        list.Add(new AtomPropertyInfo(type, p, true));
                    }
                    else
                    {
                        list.Add(new AtomPropertyInfo(type, p, false));
                    }
                }

                return list;
            }));
        }
Esempio n. 4
0
        public void Test_With_Valid_Values()
        {
            // ARRANGE
            AuditIgnoreAttribute paramAuditIgnore = new AuditIgnoreAttribute();
            ForeignKeyAttribute  paramForeignKey  = new ForeignKeyAttribute("ForeignKeyProperty");
            KeyAttribute         paramKey         = new KeyAttribute();
            NotMappedAttribute   paramNotMapped   = new NotMappedAttribute();
            RangeAttribute       paramRange       = new RangeAttribute(
                minimum: 1D,
                maximum: 5D);

            // ACT
            PropertyAttributeSummary propertyAttributeSummary = new PropertyAttributeSummary(
                auditIgnore: paramAuditIgnore,
                foreignKey: paramForeignKey,
                key: paramKey,
                notMapped: paramNotMapped,
                range: paramRange);

            // ASSERT
            Assert.AreSame(paramAuditIgnore, propertyAttributeSummary.AuditIgnore);
            Assert.AreSame(paramForeignKey, propertyAttributeSummary.ForeignKey);
            Assert.AreSame(paramKey, propertyAttributeSummary.Key);
            Assert.AreSame(paramNotMapped, propertyAttributeSummary.NotMapped);
            Assert.AreSame(paramRange, propertyAttributeSummary.Range);
        }
Esempio n. 5
0
    public static Dictionary <string, ColumnInfo> GetTableMapping <T>()
    {
        //getting properties in a specific order
        Dictionary <string, ColumnInfo> TableMapping = new Dictionary <string, ColumnInfo>();
        TypeInfo            typeInfo       = typeof(T).GetTypeInfo();
        List <PropertyInfo> properties     = new List <PropertyInfo>();
        PropertyInfo        idPropertyInfo = typeInfo.GetProperty("Id");

        if (idPropertyInfo != null)
        {
            properties.Add(typeInfo.GetProperty("Id"));                          //TODO: this is because Join reader always assume Id comes first
        }
        properties.AddRange(typeof(T).GetTypeInfo().GetProperties().Where(p => p.Name != "Id").OrderBy(p => p.Name).ToList());
        foreach (PropertyInfo p in properties)
        {
            NotMappedAttribute nm = p.GetCustomAttribute <NotMappedAttribute>();
            if (nm == null)
            {
                ColumnNameAttribute cma = p.GetCustomAttribute <ColumnNameAttribute>();
                TableMapping.Add(p.Name, new ColumnInfo {
                    ColumnName = cma != null ? cma.ColumnName : p.Name, ColumnType = p.PropertyType
                });
            }
        }
        return(TableMapping);
    }
Esempio n. 6
0
    /// <summary>
    /// Gets a comma separated string with the column names. Meant to build queries.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static string GetColumnNames(Type type)
    {
        //getting properties in a specific order
        Dictionary <string, string> Mapping = new Dictionary <string, string>();
        TypeInfo            typeInfo        = type.GetTypeInfo();
        List <PropertyInfo> properties      = new List <PropertyInfo>();
        PropertyInfo        idPropertyInfo  = typeInfo.GetProperty("Id");

        if (idPropertyInfo != null)
        {
            properties.Add(typeInfo.GetProperty("Id"));                          //TODO: this is because Join reader always assume Id comes first
        }
        properties.AddRange(typeInfo.GetProperties().Where(p => p.Name != "Id").OrderBy(p => p.Name).ToList());
        foreach (PropertyInfo p in properties)
        {
            NotMappedAttribute nm = p.GetCustomAttribute <NotMappedAttribute>();
            if (nm == null)
            {
                ColumnNameAttribute cma = p.GetCustomAttribute <ColumnNameAttribute>();
                TableAliasAttribute taa = p.GetCustomAttribute <TableAliasAttribute>();
                if (taa == null)
                {
                    throw new Exception("Table alias must be defined for each mapped attribute.");
                }
                Mapping.Add(p.Name, cma != null ? $"{taa.Alias}.{cma.ColumnName}" : $"{taa.Alias}.{p.Name}");
            }
        }
        return(String.Join(", ", Mapping.Values));
    }
Esempio n. 7
0
        /// <summary>
        /// 获取实体类键值
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public static Hashtable GetPropertyInfo <T>(T entity)
        {
            Type      type = entity.GetType();
            Hashtable ht   = new Hashtable();

            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                bool flag = true;
                foreach (Attribute attr in prop.GetCustomAttributes(true))
                {
                    NotMappedAttribute notMapped = attr as NotMappedAttribute;
                    if (notMapped != null)
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    string name  = prop.Name;
                    object value = prop.GetValue(entity, null);
                    ht[name] = value;
                }
            }
            return(ht);
        }
Esempio n. 8
0
        private void BindInfoProperty(PropertyInfo property)
        {
            Type propertyType = property.PropertyType;

            if (propertyType == typeof(Guid))
            {
                return;
            }
            DataMemberAttribute dataMember = property.GetCustomAttributes(typeof(DataMemberAttribute), false)
                                             .FirstOrDefault() as DataMemberAttribute;

            if (dataMember == null)
            {
                return;
            }
            NotMappedAttribute notMapped = property.GetCustomAttributes(typeof(NotMappedAttribute), false)
                                           .FirstOrDefault() as NotMappedAttribute;

            if (notMapped != null)
            {
                return;
            }
            DisplayNameAttribute display = property.GetCustomAttributes(typeof(DisplayNameAttribute), false)
                                           .FirstOrDefault() as DisplayNameAttribute;
            MaxLengthAttribute maxLength = property.GetCustomAttributes(typeof(MaxLengthAttribute), false)
                                           .FirstOrDefault() as MaxLengthAttribute;

            if (display == null)
            {
                return;
            }
            if (propertyType == typeof(string))
            {
                //字符串
                TextBox textBox = EditControls.FirstOrDefault(c => c.Name == typeof(TextBox).Name + property.Name) as TextBox;
                if (textBox != null)
                {
                    object value = property.GetValue(goodsAdditional, null);
                    textBox.Text = value != null?value.ToString() : "";
                }
            }
            //日期
            else if (propertyType == typeof(DateTime))
            {
                DateTimePicker dateTimePicker = EditControls.FirstOrDefault(c => c.Name == typeof(DateTimePicker).Name + property.Name) as DateTimePicker;
                if (dateTimePicker != null)
                {
                    object   value = property.GetValue(goodsAdditional, null);
                    DateTime date  = DateTime.Parse(value.ToString()).Date;
                    if (date > dateTimePicker.MinDate && date < dateTimePicker.MaxDate)
                    {
                        dateTimePicker.Value = DateTime.Parse(value.ToString());
                    }
                }
            }
        }
Esempio n. 9
0
        private void CellectProperty(PropertyInfo property)
        {
            Type propertyType = property.PropertyType;

            if (propertyType == typeof(Guid))
            {
                return;
            }
            DataMemberAttribute dataMember = property.GetCustomAttributes(typeof(DataMemberAttribute), false)
                                             .FirstOrDefault() as DataMemberAttribute;

            if (dataMember == null)
            {
                return;
            }
            NotMappedAttribute notMapped = property.GetCustomAttributes(typeof(NotMappedAttribute), false)
                                           .FirstOrDefault() as NotMappedAttribute;

            if (notMapped != null)
            {
                return;
            }
            DisplayNameAttribute display = property.GetCustomAttributes(typeof(DisplayNameAttribute), false)
                                           .FirstOrDefault() as DisplayNameAttribute;
            MaxLengthAttribute maxLength = property.GetCustomAttributes(typeof(MaxLengthAttribute), false)
                                           .FirstOrDefault() as MaxLengthAttribute;

            if (display == null)
            {
                return;
            }
            if (propertyType == typeof(string))
            {
                //字符串
                TextBox textBox = EditControls.FirstOrDefault(c => c.Name == typeof(TextBox).Name + property.Name) as TextBox;
                if (textBox != null)
                {
                    property.SetValue(goodsAdditional, textBox.Text.Trim(), null);
                }
            }
            //日期
            else if (propertyType == typeof(DateTime))
            {
                DateTimePicker dateTimePicker = EditControls.FirstOrDefault(c => c.Name == typeof(DateTimePicker).Name + property.Name) as DateTimePicker;
                if (dateTimePicker != null)
                {
                    property.SetValue(goodsAdditional, dateTimePicker.Value, null);
                }
            }
        }
Esempio n. 10
0
        private IInsqlEntityMap CreateAnnotationEntityMap(Type entityType)
        {
            TableAttribute tableAttribute = (TableAttribute)entityType.GetCustomAttribute(typeof(TableAttribute), true);

            IInsqlEntityMap resultMap = new InsqlEntityMap(entityType, tableAttribute.Name, tableAttribute.Schema);

            var columnMaps = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(propInfo =>
            {
                ColumnAttribute columnAttribute       = (ColumnAttribute)propInfo.GetCustomAttribute(typeof(ColumnAttribute), true);
                KeyAttribute keyAttribute             = (KeyAttribute)propInfo.GetCustomAttribute(typeof(KeyAttribute), true);
                NotMappedAttribute notMappedAttribute = (NotMappedAttribute)propInfo.GetCustomAttribute(typeof(NotMappedAttribute), true);
                EditableAttribute editableAttribute   = (EditableAttribute)propInfo.GetCustomAttribute(typeof(EditableAttribute), true);
                DatabaseGeneratedAttribute databaseGeneratedAttribute = (DatabaseGeneratedAttribute)propInfo.GetCustomAttribute(typeof(DatabaseGeneratedAttribute), true);

                InsqlPropertyMap propertyMap = new InsqlPropertyMap(propInfo, columnAttribute?.Name);

                if (keyAttribute != null)
                {
                    propertyMap.IsKey = true;
                }
                if (notMappedAttribute != null)
                {
                    propertyMap.IsIgnored = true;
                }
                if (databaseGeneratedAttribute != null)
                {
                    if (databaseGeneratedAttribute.DatabaseGeneratedOption == DatabaseGeneratedOption.Identity)
                    {
                        propertyMap.IsIdentity = true;
                    }
                }
                if (editableAttribute != null && !editableAttribute.AllowEdit)
                {
                    propertyMap.IsReadonly = true;
                }

                return(propertyMap);
            });

            foreach (var columnMap in columnMaps)
            {
                resultMap.Properties.Add(columnMap);
            }

            InsqlEntityValidator.Instance.Validate(resultMap);

            return(resultMap);
        }
Esempio n. 11
0
 public DbMapInfo(string dbName, string netName, Type type)
 {
     DbName  = dbName;
     NetName = netName;
     PropertyInfo[] properties = type.GetProperties(s_flag);
     ColumnMapInfos = new List <ColumnMapInfo>();
     foreach (PropertyInfo prop in properties)
     {
         KeyAttribute       attrKey    = prop.GetCustomAttribute <KeyAttribute>();
         ColumnAttribute    attrColumn = prop.GetCustomAttribute <ColumnAttribute>();
         NotMappedAttribute attrIgnore = prop.GetCustomAttribute <NotMappedAttribute>();
         bool   iskey     = attrKey != null;
         string dbColName = attrIgnore != null ? string.Empty : ((attrColumn != null && !string.IsNullOrEmpty(attrColumn.Name)) ? attrColumn.Name : prop.Name);
         ColumnMapInfos.Add(new ColumnMapInfo(dbColName, prop.Name, prop.PropertyType, iskey));
     }
     CacheColumnMapInfos = ColumnMapInfos.ToDictionary(e => e.PropName, e => e);
 }
        public static string ResolveSelect(PropertyInfo[] propertyInfos, LambdaExpression selector, int?topNum)
        {
            var selectFormat = topNum.HasValue ? " SELECT {1} {0} " : " SELECT {0} ";
            var selectSql    = "";

            if (selector == null)
            {
                var propertyBuilder = new StringBuilder();
                foreach (var propertyInfo in propertyInfos)
                {
                    NotMappedAttribute notMappedAttribute = propertyInfo.GetCustomAttribute(typeof(NotMappedAttribute)) as NotMappedAttribute;
                    if (notMappedAttribute != null)
                    {
                        continue;
                    }
                    if (propertyBuilder.Length > 0)
                    {
                        propertyBuilder.Append(",");
                    }
                    propertyBuilder.AppendFormat($"{ProviderOption.CombineFieldName(propertyInfo.GetColumnAttributeName()) } AS {  ProviderOption.CombineFieldName(propertyInfo.Name)}");
                }
                selectSql = string.Format(selectFormat, propertyBuilder, $" TOP {topNum} ");
            }
            else
            {
                var nodeType = selector.Body.NodeType;
                if (nodeType == ExpressionType.MemberAccess)
                {
                    var columnName = ((MemberExpression)selector.Body).Member.GetColumnAttributeName();
                    selectSql = string.Format(selectFormat, ProviderOption.CombineFieldName(columnName), $" TOP {topNum} ");
                }
                else if (nodeType == ExpressionType.MemberInit)
                {
                    var memberInitExpression = (MemberInitExpression)selector.Body;
                    selectSql = string.Format(selectFormat, string.Join(",", memberInitExpression.Bindings.Select(a => ProviderOption.CombineFieldName(a.Member.GetColumnAttributeName()))), $" TOP {topNum} ");
                }
                else if (nodeType == ExpressionType.New)
                {
                    var exp = (NewExpression)selector.Body;
                    selectSql = string.Format(selectFormat, string.Join(",", exp.Members.Select(a => a.GetColumnAttributeName())), $" TOP {topNum} ");
                }
            }

            return(selectSql);
        }
Esempio n. 13
0
        private void GetTableData()
        {
            TableMapping = new Dictionary <string, string>();
            PropertyInfo[] properties = typeof(T).GetTypeInfo().GetProperties();
            foreach (PropertyInfo p in properties)
            {
                NotMappedAttribute nm = p.GetCustomAttribute <NotMappedAttribute>();
                if (nm == null)
                {
                    ColumnNameAttribute cma = p.GetCustomAttribute <ColumnNameAttribute>();
                    TableMapping.Add(p.Name, cma != null ? cma.ColumnName : p.Name);
                }
            }
            TableNameAttribute tableNameAtt = typeof(T).GetTypeInfo().GetCustomAttribute <TableNameAttribute>();

            TableName = tableNameAtt != null ? tableNameAtt.TableName : typeof(T).Name + "s";
            alias     = TableName.First().ToString().ToLower();
        }
Esempio n. 14
0
        private static bool EventTypeFilter(PropertyInfo p)
        {
            NotMappedAttribute notMappedAttribute = Attribute.GetCustomAttribute(p,
                                                                                 typeof(NotMappedAttribute)) as NotMappedAttribute;

            if (notMappedAttribute != null)
            {
                return(false);
            }

            AssociationAttribute associationAttribute = Attribute.GetCustomAttribute(p,
                                                                                     typeof(AssociationAttribute)) as AssociationAttribute;

            if (associationAttribute == null)
            {
                return(true);
            }
            return(associationAttribute.IsForeignKey == false);
        }
        public static bool IsPropertyDBProperty(PropertyInfo propertyInfo)
        {
            if ((propertyInfo.PropertyType.IsValueType || propertyInfo.PropertyType.IsPrimitive ||
                 propertyInfo.PropertyType == typeof(string) || propertyInfo.PropertyType.IsEnum) &&
                (propertyInfo.GetSetMethod() != null &&
                 !(propertyInfo.PropertyType.IsGenericType && !(propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) &&
                   !propertyInfo.PropertyType.IsArray)))
            {
                NotMappedAttribute notMappedAttribute = propertyInfo.GetCustomAttribute <NotMappedAttribute>();
                ExcludeFromScriptGenerationAttribute excludeFromScriptAttribute = propertyInfo.GetCustomAttribute <ExcludeFromScriptGenerationAttribute>();

                if (notMappedAttribute == null && excludeFromScriptAttribute == null)
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="entityType"></param>
        /// <returns></returns>
        public EntityMap CreateEntityMap(Type entityType)
        {
            var map = GetEntityMap(entityType);

            if (map != null)
            {
                return(map);
            }
            map = new EntityMap(entityType);
            var tableAttr = entityType.GetCustomAttribute <TableAttribute>();

            map.TableName = string.IsNullOrEmpty(tableAttr.Name) ? entityType.Name : tableAttr.Name;


            PropertyInfo[] properties = entityType.GetProperties(s_flag);

            foreach (PropertyInfo prop in properties)
            {
                KeyAttribute       attrKey    = prop.GetCustomAttribute <KeyAttribute>();
                ColumnAttribute    attrColumn = prop.GetCustomAttribute <ColumnAttribute>();
                NotMappedAttribute attrIgnore = prop.GetCustomAttribute <NotMappedAttribute>();
                if (attrIgnore != null)
                {
                    continue;
                }
                bool   iskey     = attrKey != null;
                string dbColName = attrIgnore != null ? string.Empty : ((attrColumn != null && !string.IsNullOrEmpty(attrColumn.Name)) ? attrColumn.Name : prop.Name);
                var    pm        = new PropertyMap
                {
                    PropertyName = prop.Name,
                    ColumnName   = dbColName,
                    PropertyType = prop.PropertyType
                };
                if (iskey)
                {
                    map.KeyMaps.Add(pm);
                }
                map.PropertyMaps.Add(pm);
            }
            _cache.TryAdd(entityType, map);
            return(map);
        }
Esempio n. 17
0
File: DBEx.cs Progetto: tfwcn/blog
        /// <summary>
        /// 获取可读写公共属性
        /// </summary>
        public static PropertyInfo[] GetPropertiesPGS(this Type objType, bool?dbCanWrite)
        {
            List <PropertyInfo> properties = new List <PropertyInfo>();

            foreach (var property in objType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty))
            {
                NotMappedAttribute notMappedAttribute = Attribute.GetCustomAttribute(property, typeof(NotMappedAttribute)) as NotMappedAttribute;
                if (notMappedAttribute != null)
                {
                    continue;
                }
                //关联字段不写近数据库
                DisplayAttribute displayColumnAttribute = Attribute.GetCustomAttribute(property, typeof(DisplayAttribute)) as DisplayAttribute;
                if (dbCanWrite == null || (dbCanWrite == true && displayColumnAttribute == null))
                {
                    properties.Add(property);
                }
            }
            return(properties.ToArray());
        }
Esempio n. 18
0
        /// <summary>
        ///  获取实体对象Key
        /// </summary>
        /// <returns></returns>
        public static List <string> GetNotMappedFields <T>()
        {
            Type type = typeof(T);

            PropertyInfo[] props = type.GetProperties();
            List <string>  res   = new List <string>();

            foreach (PropertyInfo prop in props)
            {
                foreach (Attribute attr in prop.GetCustomAttributes(true))
                {
                    NotMappedAttribute keyattribute = attr as NotMappedAttribute;
                    if (keyattribute != null)
                    {
                        res.Add(prop.Name);
                    }
                }
            }
            return(res);
        }
Esempio n. 19
0
 public int Update <TEntity>(TEntity entity) where TEntity : class
 {
     VerifyExtension.Verity(entity);
     dbcontext.Set <TEntity>().Attach(entity);
     PropertyInfo[] props = entity.GetType().GetProperties();
     foreach (PropertyInfo prop in props)
     {
         NotMappedAttribute notMapped = Attribute.GetCustomAttribute(prop, typeof(NotMappedAttribute)) as NotMappedAttribute;
         if (notMapped == null)
         {
             if (prop.GetValue(entity, null) != null)
             {
                 if (prop.GetValue(entity, null).ToString() == "&nbsp;")
                 {
                     dbcontext.Entry(entity).Property(prop.Name).CurrentValue = null;
                 }
                 dbcontext.Entry(entity).Property(prop.Name).IsModified = true;
             }
         }
     }
     return(dbTransaction == null?this.Commit() : 0);
 }
Esempio n. 20
0
        private static IDictionary <string, List <PropertyInfo> > GetPropertyMappings(IEnumerable <PropertyInfo> properties, IEnumerable <string> propertyNames)
        {
            Dictionary <string, List <PropertyInfo> > mappings = new Dictionary <string, List <PropertyInfo> >();

            if (null == properties || null == propertyNames || !properties.Any())
            {
                return(mappings);
            }

            foreach (var property in properties)
            {
                if (property.IsSpecialName)
                {
                    continue;
                }

                if (null != property.GetCustomAttribute <IgnorePropertyAttribute>(true))
                {
                    continue;                                                                     //ignored (not mapped)
                }
                NotMappedAttribute notMappedAttribute = property.GetCustomAttribute <NotMappedAttribute>();

                if (null != notMappedAttribute)
                {
                    continue;                             //if not mapped then ignore
                }
                string propertyName = propertyNames.FirstOrDefault(pn => 0 == string.Compare(pn, property.Name, StringComparison.OrdinalIgnoreCase));
                if (null != propertyName)
                {
                    if (!mappings.ContainsKey(propertyName))
                    {
                        mappings[propertyName] = new List <PropertyInfo>();
                    }
                    mappings[propertyName].Add(property);
                }
            }

            return(mappings);
        }
Esempio n. 21
0
        private void UpdateNestedFieldInfo(Field fieldInfo, PropertyInfo propInfo)
        {
            fieldInfo.fieldType = FieldType.None;

            ColumnAttribute colAttr = propInfo.GetCustomAttributes <ColumnAttribute>().FirstOrDefault();

            if (colAttr != null && !string.IsNullOrEmpty(colAttr.TypeName))
            {
                if (colAttr.TypeName.ToLower() == "date")
                {
                    fieldInfo.dataType = DataType.Date;
                }
            }

            fieldInfo.isNullable = propInfo.PropertyType.IsNullableType() || (propInfo.PropertyType == typeof(string) && !propInfo.GetCustomAttributes <RequiredAttribute>().Any());
            fieldInfo.isReadOnly = fieldInfo.isAutoGenerated || propInfo.GetSetMethod() == null;

            StringLengthAttribute strLenAttr = propInfo.GetCustomAttributes <StringLengthAttribute>().FirstOrDefault();

            if (strLenAttr != null && strLenAttr.MaximumLength > 0)
            {
                fieldInfo.maxLength = strLenAttr.MaximumLength;
            }
            else
            {
                MaxLengthAttribute maxLenAttr = propInfo.GetCustomAttributes <MaxLengthAttribute>().FirstOrDefault();
                if (maxLenAttr != null && maxLenAttr.Length > 0)
                {
                    fieldInfo.maxLength = maxLenAttr.Length;
                }
            }

            NotMappedAttribute notmappedAttr = propInfo.GetCustomAttributes <NotMappedAttribute>().FirstOrDefault();

            if (notmappedAttr != null)
            {
                fieldInfo.fieldType = FieldType.ServerCalculated;
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 获取实体类键值(缓存)
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public static Hashtable GetPropertyInfo <T>(T entity)
        {
            Type type = entity.GetType();
            //object CacheEntity = CacheHelper.GetCache("CacheEntity_" + EntityAttribute.GetEntityTable<T>());
            object CacheEntity = null;

            if (CacheEntity == null)
            {
                Hashtable      ht    = new Hashtable();
                PropertyInfo[] props = type.GetProperties();
                foreach (PropertyInfo prop in props)
                {
                    bool flag = true;
                    foreach (Attribute attr in prop.GetCustomAttributes(true))
                    {
                        NotMappedAttribute notMapped = attr as NotMappedAttribute;
                        if (notMapped != null)
                        {
                            flag = false;
                            break;
                        }
                    }

                    if (flag)
                    {
                        string name  = prop.Name;
                        object value = prop.GetValue(entity, null);
                        ht[name] = value;
                    }
                }
                //CacheHelper.SetCache("CacheEntity_" + EntityAttribute.GetEntityTable<T>(), ht);
                return(ht);
            }
            else
            {
                return((Hashtable)CacheEntity);
            }
        }
Esempio n. 23
0
        public static bool IsNotMapped(this PropertyInfo property)
        {
            NotMappedAttribute attribute = (NotMappedAttribute)Attribute.GetCustomAttribute(property, typeof(NotMappedAttribute));

            return(attribute != null);
        }
Esempio n. 24
0
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="filePath">文件路径</param>
        /// <param name="models">实体数据</param>
        /// <param name="startRow">填充数据起始行</param>
        /// <param name="password">是否设置密码</param>
        /// <returns></returns>
        byte[] IExcel.ExportToByte <TModel>(string filePath, List <TModel> models, int startRow, string password)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(Path.GetFileName(filePath));
            }

            FileInfo fileInfo = new FileInfo(filePath);

            using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
            {
                ExcelWorkbook excelWorkbook = excelPackage.Workbook;

                ExcelWorksheet excelWorksheet = excelWorkbook.Worksheets[1];

                //设置Excel密码
                if (!string.IsNullOrWhiteSpace(password))
                {
                    excelWorksheet.Protection.IsProtected = true;               //设置是否进行锁定
                    excelWorksheet.Protection.SetPassword(password);            //设置密码
                    excelWorksheet.Protection.AllowAutoFilter          = false; //下面是一些锁定时权限的设置
                    excelWorksheet.Protection.AllowDeleteColumns       = false;
                    excelWorksheet.Protection.AllowDeleteRows          = false;
                    excelWorksheet.Protection.AllowEditScenarios       = false;
                    excelWorksheet.Protection.AllowEditObject          = false;
                    excelWorksheet.Protection.AllowFormatCells         = false;
                    excelWorksheet.Protection.AllowFormatColumns       = false;
                    excelWorksheet.Protection.AllowFormatRows          = false;
                    excelWorksheet.Protection.AllowInsertColumns       = false;
                    excelWorksheet.Protection.AllowInsertHyperlinks    = false;
                    excelWorksheet.Protection.AllowInsertRows          = false;
                    excelWorksheet.Protection.AllowPivotTables         = false;
                    excelWorksheet.Protection.AllowSelectLockedCells   = false;
                    excelWorksheet.Protection.AllowSelectUnlockedCells = false;
                    excelWorksheet.Protection.AllowSort = false;
                }

                //获取要反射的属性
                Type type = typeof(TModel);

                PropertyInfo[] propertyInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (TModel item in models)
                {
                    int column = 1;

                    foreach (PropertyInfo props in propertyInfo)
                    {
                        //对不映射的实体数据跳过处理
                        NotMappedAttribute notMapped = props.GetCustomAttribute(typeof(NotMappedAttribute), true) as NotMappedAttribute;

                        if (notMapped != null)
                        {
                            continue;
                        }

                        excelWorksheet.Cells[startRow, column].Value = props.GetValue(item, null);
                        //列加加
                        column++;
                    }
                    //行加加
                    startRow++;
                }

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    excelPackage.SaveAs(memoryStream);

                    return(memoryStream.ToArray());
                }
            }
        }
Esempio n. 25
0
        private void GeneratedControlByPropertyInfo(PropertyInfo property)
        {
            Type propertyType = property.PropertyType;

            if (propertyType == typeof(Guid))
            {
                return;
            }
            DataMemberAttribute dataMember = property.GetCustomAttributes(typeof(DataMemberAttribute), false)
                                             .FirstOrDefault() as DataMemberAttribute;

            if (dataMember == null)
            {
                return;
            }
            NotMappedAttribute notMapped = property.GetCustomAttributes(typeof(NotMappedAttribute), false)
                                           .FirstOrDefault() as NotMappedAttribute;

            if (notMapped != null)
            {
                return;
            }
            DisplayNameAttribute display = property.GetCustomAttributes(typeof(DisplayNameAttribute), false)
                                           .FirstOrDefault() as DisplayNameAttribute;
            MaxLengthAttribute maxLength = property.GetCustomAttributes(typeof(MaxLengthAttribute), false)
                                           .FirstOrDefault() as MaxLengthAttribute;

            if (display == null)
            {
                return;
            }
            //标签处理
            Label label = new Label();

            label.Width     = EditControlWidth / 2;
            label.Name      = label.GetType().Name + property.Name;
            label.Text      = display.DisplayName + ":";
            label.TextAlign = ContentAlignment.MiddleCenter;
            EditControls.Add(label);
            if (propertyType == typeof(string))
            {
                //字符串
                TextBox textBox = new TextBox();
                textBox.Name  = textBox.GetType().Name + property.Name;
                textBox.Width = EditControlWidth;
                //处理长度
                if (maxLength == null)
                {
                    textBox.MaxLength = 32;
                }
                else
                {
                    textBox.MaxLength = maxLength.Length / 2;
                }
                EditControls.Add(textBox);
            }
            //日期
            else if (propertyType == typeof(DateTime))
            {
                DateTimePicker dateTimePicker = new DateTimePicker();
                dateTimePicker.Name    = dateTimePicker.GetType().Name + property.Name;
                dateTimePicker.Value   = DateTime.Now;
                dateTimePicker.Width   = EditControlWidth;
                dateTimePicker.MaxDate = DateTime.Now.AddYears(100);
                dateTimePicker.MinDate = DateTime.Now.AddYears(-100);
                EditControls.Add(dateTimePicker);
            }
        }