CBO.FillCollection抛出“没有为此对象定义的无参数构造函数”。错误

时间:2009-08-13 16:02:44

标签: c# dotnetnuke dataprovider idatareader

我正在尝试从另一个方法返回的IDataReader中填充一个集合...由于某种原因,它一直在抛出“没有为此对象定义的无参数构造函数”。这一行的错误:

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

我已经尝试分离出参数,所以事情会分开初始化,直到我有了这个:

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

我在同一条线上仍然收到错误。

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

消息中的线索。 System.String没有无参数构造函数,因此无法使用Activator.CreateInstance创建它,这是通常用于动态创建对象的内容。

编辑:解决方案是直接使用阅读器:

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

答案 1 :(得分:1)

CBO.FillCollection似乎存在值类型问题。

更好的答案已经发布(直接访问读者),但要了解FillCollection方法正在寻找什么,您可以用这个来解决您的问题:

添加一个新属性,其属性设置为SQL列名:

class StringRow { public string Name; } 

使用它传递给FillCollection,如:

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

它想要一个具有命名属性的对象,它可以反射设置。因此,即使您正在检索int的列表,int对象也没有'Name'属性(从SQL返回集中的列中拉出)来设置,在这种情况下它会返回0的列表。

不幸的是,使用int?并将SQL返回列设置为[Value]并不能解决问题。