衆所周知,在向MongoDB的集合中添加一條記錄時,系統會自動增長一個字段名爲"_id",類型爲ObjectId的字段,其值爲24位字符串,能夠使用此值做爲記錄的惟一標識。spa
項目中須要調用一個已存在的MongoDB,發現其每一個collections都有一個字段"Id",而其值就是自動生成的那個"_id",這樣就存在兩個類型相同值也相同的字段,真是畫蛇添足。code
List<mgdata> items = colMsg.FindAllAs<mgdata>().SetLimit(
10).ToList<mgdata>();
當用MongoDB Driver獲取數據時,提示如下異常blog
MongoDB.Bson.BsonSerializationException: Member 'Id' of class 'yourproject' cannot use element name '_id' because it is already being used by member '_id'.
修改model以下後,可正常讀取。(經過繼承,讓"_id","Id"兩個屬性不要同時平行出現)繼承
public
class bsonItem
{
public BsonObjectId _id {
get;
set; }
}
public
class mgdata:bsonItem
{
public BsonObjectId Id {
get;
set; }
public
string name {
get;
set; }
public DateTime date {
get;
set; } }