2012-02-24 75 views
1

我在我的数据库中有一个“BSonElement”,我用标准查询重试它。BSonElement to c#数据类型

问题是我无法将BsonDocument转换为类型。

实施例:

UPDATE 1:

public partial class item_Stat 
{ 

    [BsonExtraElements] 
    public BsonDocument all_stat; 
} 

基本上,我有进入我DB 10-15属性(字段),我可以用 “BsonExtraElements” 读取。通过这种方式,我可以重试属性,而无需在C#中定义它 。

all_stat,可以有10-15-20的性质改变。 C#是键入语言,所以我不能在C#中定义这个属性,并且我使用了ExtraElements。

问题是,当我从数据库查询对象。

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 

回答

5

这里是你可以做什么的例子,因为从你的域模型就像一个类:

public class Employee 
{ 
    public ObjectId Id { get; set; } 
    public string Name { get; set; } 
} 

你可以使用你的类是这样的:

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

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

employee = collection.FindOne();</employee> 
+0

不是wath我想要 – Dada 2012-02-24 21:29:19

+0

我已更新问题 – Dada 2012-02-25 10:18:17

5

BsonElement.Value是BsonValue类型的。使用其中一个As *方法进行适当转换。这里的价值是什么?既然你有一个用户定义的类型,你最好的选择就是像Barrie上面所说的那样检索。如果您想自定义“映射”,请参考序列化教程http://www.mongodb.org/display/DOCS/CSharp+Driver+Serialization+Tutorial

+0

我已经更新了这个问题 – Dada 2012-02-25 10:18:09

1

您不能只从您的额外元素中投射BsonDocument。你必须反序列化它。

假设你有一个C类

public class C 
{ 
    public int X; 
} 

和extraDocuments变量(类似于你item_db.all_stat属性)初始化是这样的:

var extraElements = new BsonDocument(); 
var c = new C { X = 1 }; 
extraElements["c"] = c.ToBsonDocument(); 

然后,你可以提取 “C” 值并像这样反序列化:

var r = BsonSerializer.Deserialize<C>(extraElements["c"].AsBsonDocument); 
Console.WriteLine(r.ToJson());