BSonElement到c#数据类型

Dan*_*one 1 mongodb mongodb-.net-driver

我的数据库中有一个"BSonElement",我用标准查询重试它.

问题是我无法将BsonDocument转换为Type.

例:

更新1:

 public partial class item_Stat
{

    [BsonExtraElements]
    public BsonDocument all_stat;
}
Run Code Online (Sandbox Code Playgroud)

基本上,我已经进入我的DB 10-15属性(字段),我可以用"BsonExtraElements"阅读.通过这种方式,我可以重试属性而无需在C#中定义它.

all_stat,可以有10-15-20属性,在dinamically变化.C#是键入的语言,所以我无法在C#中定义此属性,并且我使用了ExtraElements.

问题是当我从DB查询对象时.

var item_db = myMongoCollection.find(theQuery); // find the OBJECT

item_db.all_stat // all the property hare HERE

// find the property "category_01"
var i =  item_db.all_stat.Where(p => p.Name == "category_01").Single();

// ok, i have found the Category, so i can cast it to C# Data Type    
var typed_value = (ItemStatSingle) i.Value // BsonElement to ItemStatSingle
Run Code Online (Sandbox Code Playgroud)

小智 5

以下是您可以执行的操作示例,给出了域模型中的类,例如:

public class Employee
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您可以像这样使用您的类:

var collection = database.GetCollection<employee>("employees");

var employee = new Employee { Name = "John Smith" };
collection.Insert(employee);

employee = collection.FindOne();</employee>
Run Code Online (Sandbox Code Playgroud)


Sri*_*ran 5

BsonElement.Value的类型为BsonValue.使用As*方法之一进行适当的转换.这里的价值是什么类型的?由于您拥有用户定义的类型,因此最佳选择是检索Barrie上面所说的.如果要自定义"映射",请参阅序列化教程http://www.mongodb.org/display/DOCS/CSharp+Driver+Serialization+Tutorial