2012-02-24 74 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());