我有一个具有KeyValuePair类型属性的对象。
我想从数据库中读取一些数据并将结果存储在此KeyValuePair类型字段中。
myObject.KeyValuePairs = ctx.ExecuteQuery<KeyValuePair<String, int>>
("Select " +
"[" + q.Name + "] As [Key]" +
", Count([" + q.Name + "]) As [Value] From SomeTable" +
" Group By [" + q.Name + "]").ToList();
myObject.KeyValuePairs
是List<KeyValuePair<String, int>>
当我尝试读取记录时,我得到以下异常:
类型'System.Collections.Generic.KeyValuePair`2 [System.String,System.Int32]'必须声明一个默认(无参数)构造函数才能在映射期间构造。
我在类中有一个默认构造函数,但这不是解决问题的方法。它看起来好像不知道如何构造KeyValuePair对象。它没有默认构造函数吗?困惑..
谢谢
答案 0 :(得分:14)
它有一个公共无参数构造函数,因为KeyValuePair<TKey, TValue>
是一个结构,所有结构都有隐式公共无参数构造函数。
问题是EF无法通过反射找到它,因为反射不会返回struct的默认构造函数。
这就是为什么EF报告无法找到它(它无法通过反射找到它)。
此外,即使您可以通过反射使用默认构造函数,KeyValuePair<TKey, TValue>
也是不可变的,因此您无法在构建后设置Key
和Value
。
要解决您的问题,请定义自定义类
class NameCount {
public string Name { get; set; }
public int Count { get; set; }
}
并更改您的查询,将Key
返回为Name
,将Value
返回为Count
。我假设您可以为自定义类提供更好的名称。