[英]MongoDB c# driver - Can a field called Id not be Id?
更特別的是,有一堂課
class X {
....
string Id { get; set; }
}
class Y : X {
ObjectId MyId { get; set; }
}
我希望MyId成為Y的id,即映射到_id。
可能嗎?
我在這段代碼后得到一個例外:
var ys = database.GetCollection("ys");
ys.InsertBatch(new Y[] { new Y(), new Y()});
例外情況:{“類'MongoTest1.Y'的成員'MyId'不能使用元素名稱'_id',因為它已被成員'Id'使用。”}
完整的測試案例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
namespace MongoTest1
{
class X
{
public string Id { get; set; }
}
class Y : X
{
public ObjectId MyId { get; set; }
}
class Program
{
static Program() {
BsonClassMap.RegisterClassMap<X>(cm =>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(c => c.Id));
});
BsonClassMap.RegisterClassMap<Y>(cm =>
{
cm.AutoMap();
cm.SetIdMember(cm.GetMemberMap(c => c.MyId));
});
}
static void Main(string[] args)
{
var server = MongoServer.Create("mongodb://evgeny:evgeny@localhost:27017/test");
var database = server.GetDatabase("test");
using (server.RequestStart(database))
{
var ys = database.GetCollection("ys");
ys.InsertBatch(
new Y[] {
new Y(), new Y()
}
);
}
}
}
}
X的Id必須是字符串。
你的問題的答案是“是的,但是......”。
有可能有一個名為ID的部件,其不被映射到_id元件。 例如:
public class X {
[BsonId]
public ObjectId MyId;
}
public class Y : X {
public string Id;
}
但是,在類層次結構中,_id成員必須位於層次結構的根目錄中(換句話說,層次結構的所有成員必須同意使用相同的_id)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.