I have a question on generics. I am trying to convert my code using generic so I don’t need to change my code again for every specific type like CompanyBO, EmployeeBO etc…
Here is my code:
public List<T1> GetAllEmployees<T1>()
{
try
{
var objEmployeeList = new List<T1>();
SqlConnection objSqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString);
if (objSqlCon.State == System.Data.ConnectionState.Closed)
{
objSqlCon.Open();
}
SqlCommand objSqlCmd = new SqlCommand("SELECT EmployeeID, ContactID, LoginID, Title FROM HumanResources.Employee", objSqlCon);
SqlDataReader objSqlDataRead;
objSqlDataRead = objSqlCmd.ExecuteReader();
while (objSqlDataRead.Read())
{
objEmployeeList.Add(FillDataRecord(objSqlDataRead));
}
return objEmployeeList;
}
catch (Exception ex)
{
throw ex;
}
}
private EmployeeBO FillDataRecord(IDataRecord objDataRecord)
{
try
{
EmployeeBO objEmployeeBO = new EmployeeBO();
if (!objDataRecord.IsDBNull(objDataRecord.GetOrdinal("EmployeeID")))
{
objEmployeeBO.EmployeeID = objDataRecord.GetInt32(objDataRecord.GetOrdinal("EmployeeID"));
}
if (!objDataRecord.IsDBNull(objDataRecord.GetOrdinal("ContactID")))
{
objEmployeeBO.ContactID = objDataRecord.GetInt32(objDataRecord.GetOrdinal("ContactID"));
}
if (!objDataRecord.IsDBNull(objDataRecord.GetOrdinal("Title")))
{
objEmployeeBO.Title = objDataRecord.GetString(objDataRecord.GetOrdinal("Title"));
}
if (!objDataRecord.IsDBNull(objDataRecord.GetOrdinal("LoginID")))
{
objEmployeeBO.LoginID = objDataRecord.GetString(objDataRecord.GetOrdinal("LoginID"));
}
return objEmployeeBO;
}
catch (Exception ex)
{
throw ex;
}
}
I am getting 1 error : cannot convert from ‘EmployeeBO’ to ‘T1’
Can any please help me to create this Generic Method…
Your
FillDataRecordcan only ever return anEmployeeBO, so it’s not clear why you want to use generics in the first place. Why would a name called GetAllEmployees want to return aList<CompanyBO>for example?It looks like you should just change the signature to:
and make the corresponding change within the method.
If you want to write a generic method, you should work out what would change between this method and the corresponding method for companies. I would suggest that in the current design, it would be:
IDataRecordinto an entitySo that would suggest you have something like:
You’d then specify the converter using a method group conversion, e.g.
Is there any reason you want to build your own sort of ORM for this rather than using some of the many existing ones, by the way?