2012-11-22 106 views
0

我正在进行相对调整MongoDB MapReduce demo in C#C#中的MongoDB MapReduce问题

的代码如下:

public List<CategorySummaryResult> GetCategorySummaries() 
    { 
     string map = @" 
      function() { 
       var key = this.FeedType; 
       var value = {count: 1, names: this.Name}; 
       emit(key, value); 
      }"; 

     string reduce = @" 
      function(key, values) { 
       var result = {count: 0, names: ''}; 

       values.forEach(function(value) { 
        result.count += value.count; 
        result.names += ',' + value.names; 
       }); 

       return result; 
      }"; 

     string finalize = @" 
      function(key, value) { 
       if (value.names.charAt(0) === ',') 
        value.names = value.names.substr(1); 

       return value;     
      }"; 

     var options = 
      MapReduceOptions 
       .SetFinalize(finalize) 
       .SetOutput(MapReduceOutput.Inline); 

     var result = 
      _db.GetCollection("NewsCategories") 
       .MapReduce(map, reduce, options) 
       .GetInlineResultsAs<CategorySummaryResult>() 
       .ToList(); 

     return result; 
    } 

对象反序列化到:

public class CategorySummaryResult 
{ 
    public double id { get; set; } 
    public ICollection<CategorySummary> value { get; set; } 
} 

public class CategorySummary 
{ 
    public double count { get; set; } 
    public string names { get; set; } 
} 

这里的BSON输出的样子:

[0]: { "_id" : 1.0, "value" : { "count" : 3.0, "names" : "Games,Technologie,Auto" } } 
[1]: { "_id" : 2.0, "value" : { "count" : 1.0, "names" : "Hoofdpunten" } } 

不过,我不断收到以下例外:

An error occurred while deserializing the value property of class MetroNews.Managers.CategorySummaryResult: 
Expected element name to be '_t', not 'count'. 

怎么回事和我该如何解决它

回答

1

您无法正确序列化/反序列化ICollection。

它会很好地序列化到任何对象的列表中,但是当您想要反序列化时会出现问题。

解串器无法实例化ICollection,也不知道要使用哪种特定类型,而无需通过约定指定它。

你应该改变

public class CategorySummaryResult 
{ 
    public double id { get; set; } 
    public ICollection<CategorySummary> value { get; set; } 
} 

喜欢的东西

public class CategorySummaryResult 
{ 
    public double id { get; set; } 
    public List<CategorySummary> value { get; set; } 
} 
+0

Thx为提示。我已经试过了,没有雪茄:/ – David

+0

,你确定你的mongodb没有被旧数据“污染”? –

+0

上面发布的非反序列化数据看起来很好。 错误在于反序列化。 – David

0

尝试增加[BsonDiscriminatorAttribute(required=true)]CategorySummary类。