Generic List Problem

R

Radenko Zec

Hi i have generic list problem with DAL code.


class UlazTotal

{




private System.DateTime uT_DATUMField;

private string rA_SIFRAField;

private decimal uT_IZNOSField;

..........

public System.DateTime UT_DATUM

{

get

{return this.uT_DATUMField;}

set

{this.uT_DATUMField = value;}

}


public string RA_SIFRA

{

get

{return this.rA_SIFRAField;}

set

{this.rA_SIFRAField = value;}

}


public decimal UT_IZNOS

{

get

{return this.uT_IZNOSField;}

set

{this.uT_IZNOSField = value;}

}.........................


}

I want to make generic method for getting all data from any class in solution.

public static List<T> GetAll<T>(List<T> source) where T: new()

{

List<T> lista = new List<T>();

SqlParameter[] parameters =

{};

SqlDataReader dr = SqlHelper.ExecuteReader(NoviTemplate.SqlHelper.ConnStr(), CommandType.StoredProcedure, "sp_UlazTotal_GetAll");

while (dr.Read())

{

T obj;

obj=new T();

Read(obj, dr); /////////////////HERE I GET ERROR

}

dr.Close();

return lista;

}



private static void Read(UlazTotal ulazTotal, SqlDataReader dr)

{

UlazTotal ulazTotal = new UlazTotal() ;

ulazTotal.UT_DATUM = Convert.ToDateTime(dr["UT_DATUM"].ToString());

ulazTotal.RA_SIFRA = dr["RA_SIFRA"].ToString();

ulazTotal.UT_IZNOS = Convert.ToDecimal(dr["UT_IZNOS"].ToString());

...............

}



How to make Generic Read method that accept any class (not ulazTotal class) and populate properties of any class with data from reader?



Thanks
 
M

Marc Gravell

Well, you aren't going to be able to use the properties of the class
in this way, so I wouldn't even bother typing it... you are going to
have to use reflection or component-model access - something like:

void Read(object obj, IDataReader reader) {
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(obj);
for(int field = 0; field < reader.Fields; field++) {
PropertyDescriptor prop = props[reader.GetName(field)];
if(prop!=nulll) {
prop.SetValue(obj, reader[field]);
}
}
}

However - this is a very crude approach; perhaps look at ORMs like
NHibernate? Or LINQ in .NET 3.5? In these cases the object type comes
into play, so I might make it:

void Read<T>(T obj, IDataReader reader) {...}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top