I have have attempted to use generics and constraints to create functions that retrieve and save data from a number of similar objects. Each of these objects describe their own properties. When I use these methods for a particular Type I don't understand why I have to specify new()
new() in the constraint and also create a new version of the type in order to access its underlying properties to assist me. I'm sure there is a better way, but my knowledge in this area is a little lacking.
There are a number of objects that inherit from RawDataAggregatedItem
RawDataAggregatedItem.
RawDataAggregatedItem
RawDataAggregatedItem has itsit's own interface:
public RawDataAggregatedItems<T>RawDataAggregatedItems<T> GetRawDataAggregated<T>GetRawDataAggregated<T>(int? id) where T : IRawDataAggregatedItem, <strong><em>new()</em></strong>new()
{
try
{
<strong><em>var itemType = new T();</em></strong>var itemType = new T();
using (var cn = Connection())
{
var cmd = new SqlCommand(<strong><em>itemType.GetStoredProcedureName</em></strong>itemType.GetStoredProcedureName, cn) { CommandTimeout = _commandTimeout, CommandType = CommandType.StoredProcedure };
cmd.Parameters.Add(new SqlParameter("@periodId""@periodId", SqlDbType.Int)).Value = id;
return new RawDataAggregatedItems<T>RawDataAggregatedItems<T>(cmd.ExecuteReader());
}
}
catch (Exception ex)
{
throw new Exception("Error"Error fetching aggregated rawdata list."", ex);
}
}
public void UpdateRawDataAggregated(RawDataAggregatedItem itemToUpdate)
{
try
{
using (var cn = Connection())
{
var cmd = new SqlCommand(<strong><em>itemToUpdate.UpdateStoredProcedureName</em></strong>itemToUpdate.UpdateStoredProcedureName, cn) { CommandTimeout = _commandTimeout, CommandType = CommandType.StoredProcedure };
cmd.Parameters.Add(new SqlParameter("@projectid""@projectid", SqlDbType.VarChar)).Value = ((IRawDataAggregatedItem)itemToUpdate).ID;
cmd.Parameters.Add(new SqlParameter("@is_flagged""@is_flagged", SqlDbType.Bit)).Value = ((IRawDataAggregatedItem)itemToUpdate).isFlaggedForReview;
cmd.Parameters.Add(new SqlParameter("@is_reviewed""@is_reviewed", SqlDbType.Bit)).Value = ((IRawDataAggregatedItem)itemToUpdate).isReviewed;
cmd.ExecuteReader();
}
}
catch (Exception ex)
{
throw new Exception("Error"Error updating aggregated rawdata item."", ex);
}
}
ItIf feels a bit wrong to
- Supplysupply
new()
in theGetRawDataAggregated
constraint but the compiler is forcing me to. - New-ing up a Type
T
(var itemType = new T()
) in order to get toT.Property
.
CouldPlease could you please suggest a better way of doing this?