简体   繁体   中英

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

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, ie 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM