KeyValuePair

编程入门 行业动态 更新时间:2024-10-27 08:40:33
本文介绍了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

本文发布于:2023-11-09 06:23:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:KeyValuePair

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!