MongoDB c# driver - Can a field called Id not be Id?

喜欢而已 提交于 2019-12-01 18:33:39

问题


More particulary, there is a class

class X {
       ....
       string Id { get; set; }
}

class Y : X {
       ObjectId MyId { get; set; }
}

I would like MyId to be an id for Y, i.e. to be mapped to _id.

Is it possible?

I get an exception after this code:

var ys = database.GetCollection("ys"); 
ys.InsertBatch(new Y[] { new Y(), new Y()}); 

The exception: {"Member 'MyId' of class 'MongoTest1.Y' cannot use element name '_id' because it is already being used by member 'Id'."}

Full test case:

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's Id MUST be string.


回答1:


The answer to your question is "yes, but...".

It is possible to have a member called Id which is not mapped to the _id element. For example:

public class X {
    [BsonId]
    public ObjectId MyId;
}

public class Y : X {
    public string Id;
}

However, in a class hierarchy the _id member must be at the root of the hierarchy (in other words, all members of the hierarchy must agree on using the same _id).



来源:https://stackoverflow.com/questions/7228609/mongodb-c-sharp-driver-can-a-field-called-id-not-be-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!