Development of a lot of people will use BLL model this development, I also, although there are a lot of automatic generation tools, can be generated in a few seconds cs template, but I personally do not like, I still like to write their own, so better understand their own code.
However, the manual writing, the most annoying is the getmodel such methods, the DataRow data into a model, really write my headache, because a lot of code is basically the same, always want to use reflection to write such a method, In the future, just call a method to complete the model assignment, which is convenient. I'm having this kind of code again today, for a while, he wrote a method, using the principle of reflection (learned from the BlogEngine), perhaps this method is more clumsy, perhaps there are other better ways to achieve, but at present it is able to meet the needs of my getmodel, but also live to put up, I hope you can give me a better suggestion.
Nonsense not to say the code is as follows:
public class ModelHelper <T> where T : new()
{
public static T ConvertModel(DataRow dr)
{
T 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 type)
{
if (obj == DBNull.Value)
{
obj = default(object);
}
else
{
obj = Convert.ChangeType(obj, type);
}
return obj;
}
}
Example:
Model model = ModelHelper<Model>.ConvertModel(DataRow)
Convertmodel static method is converted, Getdefaultvalue method is to get the default value of object, because the value taken from DataRow, sometimes dbnull, if the direct assignment will be throw wrong.
A bad place:
1, the model class must be with the DataRow column name one by one correspondence
2, model Class I set up must have a destructor
The code may not be very ideal, hope the heroes are pointing twos.
Email:dally_2000@163.com