KeyValuePair - no parameterless constructor?
I have an object that has a KeyValuePair type property.
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
is a List<KeyValuePair<String,开发者_运维技巧 int>>
When I attempt to read the records I get the following exception:
The type 'System.Collections.Generic.KeyValuePair`2[System.String,System.Int32]' must declare a default (parameterless) constructor in order to be constructed during mapping.
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..
Thank you
It does have a public parameterless constructor because KeyValuePair<TKey, TValue>
is a struct and all struct have implicit public parameterless constructor.
The issue is that EF can't find it by reflection because reflection does not return the default constructor for struct.
This is why EF is reporting that it can't find it (it can't find it by reflection).
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; }
}
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.
精彩评论