Many developers use BLL model development. I am also familiar with it. Although there are many automatic generation tools that can generate a CS template within several seconds, I personally do not like it very much, I still like writing one by myself, so that I can better understand my ownCode.
However, when writing data manually, the most annoying method is GetModel, which converts the data of datarow into a model. It is really a headache for me, because many codes are basically the same, I always wanted to use reflection to write such a method. In the future, only one method can be called to complete the model assignment, which is convenient. Today, I encountered this kind of code. I wrote a method and adopted the reflection principle (learned from blogengine). Maybe this method is clumsy, there may be other better methods to achieve this, but at present it can meet the needs of my GetModel, and I hope you can give me better suggestions.
The Code is as follows:
Code
Public Class Modelhelper < T > Where T: New ()
{
Public Static T convertmodel (datarow Dr)
{
T = New T ();
Type modeltype = T. GetType ();
Foreach (Propertyinfo P In Modeltype. getproperties ())
{
P. setvalue (T, getdefaultvalue (Dr [P. name], p. propertytype ), Null );
}
Return T;
}
Private Static Object Getdefaultvalue ( Object OBJ, type)
{
If (OBJ = Dbnull. value)
{
OBJ = Default ( Object );
}
Else
{
OBJ = Convert. changetype (OBJ, type );
}
Return OBJ;
}
}
Example:
Code
Model=Modelhelper<Model>. Convertmodel (datarow)
The convertmodel static method is converted. The getdefaultvalue method is used to obtain the default value of the object, because the value obtained from datarow is sometimes dbnull. If the value is assigned directly, throw is incorrect.
Bad:
1. The model class must correspond to the column names of datarow.
2. The model class must have a destructor.
The Code may not be ideal. I hope you can give me some advice.
Email: dally_2000@163.com
PS: Tomorrow is Christmas Eve. Hope you have a good time.
PS2: Good brother's father has gone. Sorry, may he be happy in heaven
PS3: I have made a website for my wife. I hope you can leave a message to me.
Web: http://www.yangwenjie.cn/flash.html