我正在學習MongoDB,我想用C#嘗試它。是否可以使用C#官方MongoDB驅動程序對強類型的MongoDB文檔進行操作?mongoDB,使用C#官方驅動程序的強類型集合
我有類Album
和Photo
:
public class Album : IEnumerable<Photo>
{
[Required]
[BsonElement("name")]
public string Name { get; set; }
[Required]
[BsonElement("description")]
public string Description { get; set; }
[BsonElement("owner")]
public string Owner { get; set; }
[BsonElement("title_photo")]
public Photo TitlePhoto { get; set; }
[BsonElement("pictures")]
public List<Photo> Pictures { get; set; }
//rest of the class code
}
public class Photo : IEquatable<Photo>
{
[BsonElement("name")]
public string Name;
[BsonElement("description")]
public string Description;
[BsonElement("path")]
public string ServerPath;
//rest of the class code
}
我要插入一個新的文檔到一個集合albums
在test
數據庫。我不想在BsonDocument
上操作,但我更願意使用強類型Album
。我認爲這將是這樣的:
IMongoClient client = new MongoClient();
IMongoDatabase db = client.GetDatabase("test");
IMongoCollection<Album> collection = database.GetCollection<Album>("album");
var document = new Album
{
Name = album.Name,
Owner = HttpContext.Current.User.Identity.Name,
Description = album.Description,
TitlePhoto = album.TitlePhoto,
Pictures = album.Pictures
};
collection.InsertOne(document);
但它給我下面的錯誤:
An exception of type 'MongoDB.Driver.MongoCommandException' occurred in MongoDB.Driver.Core.dll but was not handled in user code
Additional information: Command insert failed: error parsing element 0 of field documents :: caused by :: wrong type for '0' field, expected object, found 0: [].
什麼我做錯了,如果有可能實現嗎?
[這可能是幫助](http://www.codeproject.com/Articles/273145/Using-MongoDB-with-the-Official-Csharp-Driver) – Chandralal