1

私の 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);
                }
            }
        }

残念ながら、上記の方法はジェネリックのリストを処理できず、実装方法がわかりません。

誰かが私を助けることができますか?

4

0 に答える 0