MongoDB的C#驱动程序 - 可以被称为Id字段没有标识? [英] MongoDB c# driver - Can a field called Id not be Id?

查看:359
本文介绍了MongoDB的C#驱动程序 - 可以被称为Id字段没有标识?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更格外,还有一类

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

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



我想MYID是Y的一个ID,即映射要_id

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

是否有可能

我得到这个代码后的异常:

I get an exception after this code:

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



例外:
{级会员身份识别码'MongoTest1.Y'不能使用元素名称'_id',因为它已被用于会员'ID'}

The exception: {"Member 'MyId' of class 'MongoTest1.Y' cannot use element name '_id' because it is already being used by member '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必须是字符串。

X's Id MUST be string.

推荐答案

在回答你的问题是是的,但是......。

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

它的的可能有一个成员叫编号是的的映射到_id元素。例如:

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;
}

然而,在一个类层次的_id成员的必须处于层次结构的根(换句话说,层次结构的所有成员必须同意使用相同的_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).

这篇关于MongoDB的C#驱动程序 - 可以被称为Id字段没有标识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆