自动截取Entity实体属性中字符串超长字符

因为项目中有部分接口是通过WCF暴露的,所以需要对每一个返回来的数据进行检查(通常其他类型都会在客户端完成验证,而字符串长度必须在服务端控制),特设计的一种通用针对字符串超长的处理实现;

大概思路是:

1.通过反射先获取实体中所有为String类型的属性;

2.根据实体属性名称查找实体元数据中的属性;

3.查找属性中包含MaxLength的参数;

4.通过反射获取属性值;

5.根据MaxLength值截取超长的字符串;

6.再通过反射将属性设置为更改后的值;

Code:


        
/// <summary>
        
/// 自动截取实体对象属性中字符串最大长度
        
/// </summary>
        
/// <param name="entitySet">实体集</param>
        
/// <typeparam name="T">实体对象类型</typeparam>
        
/// <param name="model">实体对象</param>
        
/// <returns></returns>
        public T SubStringMaxLength<T>(EntitySet entitySet,T model) where T : EntityObject
        {
            Type t 
= model.GetType();
            
// 1.先获取所有实体中为String类型的属性;
            var arrProperty = t.GetProperties().Where(p=>p.PropertyType == typeof(string));
            
//循环遍历属性
            foreach (var property in arrProperty)
            {
                    
string propertyName = property.Name;
                    
// 2.根据实体属性名称查找实体元数据中的属性
                    EdmProperty edmproperty = entitySet.ElementType.Properties.First(p => p.Name == propertyName);
                    
if (edmproperty != null)
                    {
                        
// 3.查找属性中包含MaxLength的参数
                        Facet facLength = edmproperty.TypeUsage.Facets.First(p => p.Name == "MaxLength");
                        
if (facLength != null) ;
                        {
                            
int maxLength = Convert.ToInt32(facLength.Value);
                            
//  4.通过反射获取属性值
                            object objValue = property.GetValue(model, null);
                            
if (objValue != null)
                            {
                                
// 5.根据MaxLength值截取超长的字符串(保留左边字符)
                                string value = StringHelper.SubstringLeft(objValue.ToString(), maxLength);
                                
// 6.再通过反射将属性设置为更改后的值
                                if (!string.IsNullOrEmpty(value))
                                    property.SetValue(model, value, 
null);
                            }
                        }
                }
            }
            
return model;
        }

本例只是提供一种思路;前提是概念模型中的MaxLength值必须和数据库中长度值一致;这种方案可能会影响一点点性能,但可以减少不是代码开发量;

Demo下载:https://files.cnblogs.com/yizhuqing/AutoSubstringEntityAttr.rar

作者:柱子
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/yizhuqing/p/AutoSubstringEntityAttr.html