views:

205

answers:

2

I'm trying to fill a collection from an IDataReader that was returned by another method... for some reason it keeps throwing a "No parameterless constructor defined for this object." error for this line:

List<string> names = CBO.FillCollection<string>(DataProvider.Instance().ExecuteReader("getNames", new SqlParameter("UserId", 1)));

I've tried separating out the parameters so things get initialized separately until I had this:

List<string> names = CBO.FillCollection<string>(nameDataReader);

and I was still getting an error on the same line.

Any ideas?

+3  A: 

The clue's in the message. There's no parameterless constructor for System.String, so it can't be created using Activator.CreateInstance, which is what is usually used to dynamically create objects.

EDIT: A solution would be to use the reader directly:

var strings = new List<string>();
using(var reader = DataProvider.Instance().ExecuteReader("getNames", new SqlParameter("UserId", 1)))
{
    while(reader.Read()) 
        strings.Add(reader[0] as string);
}
David Kemp
So what do I have to do...?
Matt
Have added a possible solution - hth
David Kemp
Awesome, thanks!
Matt
A: 

CBO.FillCollection seems to have an issue with value types.

The better answer is already posted (access the reader directly), but to understand what the FillCollection method is looking for, you could have solved your problem with this:

Add a new class with a property set to your SQL column name:

class StringRow { public string Name; } 

Use it to pass to FillCollection, like:

List<string> stringCollection = new List<string>();
foreach (StringRow row in CBO.FillCollection<StringRow>(DataProvider...)) 
{
    stringCollection.Add(row.Name);
}

It wants an object with a named property it can reflectively set. So even if you were retrieving a list of int, the int object doesn't have a 'Name' property (pulled from the column in the SQL return set) to set, in which case it would return a list of 0s.

Unfortunately, using int? and setting the SQL return column to [Value] does not remedy the solution.

Spencer Creasey