在我的 WinForm 应用程序中,我实际上正在使用该LightweightDAL
项目,它提供了一种很好的方法来填充我的数据模型。除了设置为另一个模型列表的属性外,一切正常。这是我的模型课:
public class SchedaFamiglia
{
[DBField("Id")]
public int Id { get; set; }
[DBField("IdFamiglia")]
public int IdFamiglia { get; set; }
[DBField("IdMamma")]
public int IdMamma { get; set; }
[DBField("IdPapa")]
public int IdPapa { get; set; }
[DBField("IdBambino")]
public List<SchedaBambino> Figli { get; set; }
public SchedaFamiglia()
{
}}
上面的模型SchedaBambino
只是一个基本类型属性的列表(int32、string...)。
这是GetItemFromReader
方法的片段:
private static T GetItemFromReader<T>(IDataReader rdr) where T : class
{
Type type = typeof(T);
T item = Activator.CreateInstance<T>();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
// for each property declared in the type provided check if the property is
// decorated with the DBField attribute
if (Attribute.IsDefined(property, typeof(DBFieldAttribute)))
{
DBFieldAttribute attrib = (DBFieldAttribute)Attribute.GetCustomAttribute(property, typeof(DBFieldAttribute));
if (Convert.IsDBNull(rdr[attrib.FieldName])) // data in database is null, so do not set the value of the property
continue;
if (property.PropertyType == rdr[attrib.FieldName].GetType()) // if the property and database field are the same
property.SetValue(item, rdr[attrib.FieldName], null); // set the value of property
else
{
// change the type of the data in table to that of property and set the value of the property
property.SetValue(item, Convert.ChangeType(rdr[attrib.FieldName], property.PropertyType), null);
}
}
}
不幸的是,上面的方法无法处理通用列表,我不知道如何实现。
有人可以帮助我吗?