Because some interfaces in the project are exposed through WCF, you need to check the data returned for each response (other types of data are usually verified on the client, and the string length must be controlled on the server ), it is a general implementation of processing character strings that are too long;
The general idea is:
1. Obtain all attributes of the string type in the object through reflection;
2. Search for attributes in the object metadata based on the object property name;
3. Search for parameters whose attributes contain maxlength;
4. Get the property value through reflection;
5. Extract ultra-long strings Based on the maxlength value;
6. Set the property to the changed value through reflection;
Code:
/// <Summary>
/// Automatically intercepts the maximum length of a string in object attributes.
/// </Summary>
/// <Param name = "entityset"> Entity set </Param>
/// <Typeparam name = "T"> Object Type </Typeparam>
/// <Param name = "model"> Object </Param>
/// <Returns> </returns>
Public T substringmaxlength < T > (Entityset, T Model) Where T: entityobject
{
Type T = Model. GetType ();
// 1. First, obtain the attributes of the string type in all entities;
VaR arrproperty = T. getproperties (). Where (P => P. propertytype = Typeof ( String ));
// Loop traversal attributes
Foreach (VAR Property In Arrproperty)
{
String Propertyname = Property. Name;
// 2. Search for attributes in the object metadata based on the object property name
Edmproperty = Entityset. elementtype. properties. First (P => P. Name = Propertyname );
If (Edmproperty ! = Null )
{
// 3. Search for parameters whose attributes contain maxlength
Facet faclength = Edmproperty. typeusage. facets. First (P => P. Name = " Maxlength " );
If (Faclength ! = Null );
{
Int Maxlength = Convert. toint32 (faclength. value );
// 4. Get attribute values through reflection
Object Objvalue = Property. getvalue (model, Null );
If (Objvalue ! = Null )
{
// 5. extract extra-long strings Based on the maxlength value (retain the characters on the left)
String Value = Stringhelper. substringleft (objvalue. tostring (), maxlength );
// 6. Set the property to the changed value through reflection.
If ( ! String . Isnullorempty (value ))
Property. setvalue (model, value, Null );
}
}
}
}
Return Model;
}
This example only provides an idea. The premise is that the maxlength value in the conceptual model must be consistent with the length value in the database. This solution may affect a little bit of performance, but can reduce the numberCodeDevelopment volume;
Demo download: http://files.cnblogs.com/yizhuqing/AutoSubstringEntityAttr.rar