KeyValuePair-没有无参数的构造函数? [英] KeyValuePair - no parameterless constructor?

查看:62
本文介绍了KeyValuePair-没有无参数的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有KeyValuePair类型属性的对象.

I have an object that has a KeyValuePair type property.

我想从数据库中读取一些数据并将结果存储在此KeyValuePair类型字段中.

I would like to read some data from a database and store results in this KeyValuePair type field.

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>>

当我尝试读取记录时,出现以下异常:

When I attempt to read the records I get the following exception:

类型"System.Collections.Generic.KeyValuePair`2 [System.String,System.Int32]"必须声明默认的(无参数)构造函数,以便在映射期间进行构造.

The type 'System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]' must declare a default (parameterless) constructor in order to be constructed during mapping.

我在一个类中有一个默认的构造函数,但这不能解决问题.看起来好像它不知道如何构造KeyValuePair对象.它没有默认的构造函数吗?糊涂了.

I have a default constructor in a class, but this is not fixing the problem. It looks as if It doesn't know how to construct a KeyValuePair object. Doesn't it have a default constructor? Confused..

谢谢

推荐答案

它确实具有公共的无参数构造函数,因为 KeyValuePair< TKey,TValue> 是一个结构,并且所有结构都具有隐式的公共无参数构造函数.

It does have a public parameterless constructor because KeyValuePair<TKey, TValue> is a struct and all struct have implicit public parameterless constructor.

问题在于EF无法通过反射找到它,因为反射不会返回struct的默认构造函数.

这就是为什么EF报告它找不到它(它无法通过反射找到它).

This is why EF is reporting that it can't find it (it can't find it by reflection).

此外,即使您可以通过反射使用默认构造函数, KeyValuePair< TKey,TValue> 也是不可变的,因此您无法设置 Key 价值构建后.

Additionally, even if you could use the default constructor by reflection, KeyValuePair<TKey, TValue> is immutable and so you can't set the Key and Value after construction.

要解决您的问题,请定义一个自定义类

To solve your problem, define a custom class

class NameCount {
    public string Name { get; set; }
    public int Count { get; set; }
}

并更改查询以将 Key 作为 Name 返回,并将 Value 作为 Count 返回.我认为您可以为自定义类命名一个更好的名称.

and change your query to return the Key as Name and Value as Count. I assume that you can come up with a better name for your custom class.

这篇关于KeyValuePair-没有无参数的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆