子文档中的Id在Mongo C#驱动程序中序列化为_id

时间:2018-06-18 22:41:46

标签: c# mongodb

我有一个看起来像这样的课程:

   public class SyncData<T>
   {
        [BsonId]
        [BsonIgnoreIfDefault]
        public ObjectId MongoId { get; set; }

        [BsonIgnore]
        public string Id => MongoId.ToString();

        public T Data { get; set; }

        //etc.

   }

有时,Data对象有一个Id字段,C#在将其保存到Mongo时会自动序列化为_id。

如何让它停止将Id序列化为_id而无需访问通用T Data属性中存储的任何类型。

1 个答案:

答案 0 :(得分:0)

如果您以某种方式预先了解类型:

给定类型

#!/bin/sh
# git-fetch-log: Ultimate git fetch-log
#
# It shows the diferences of `local...remote` if both side exists and there
# are differences. Useful to find out what you have to do: `merge`, `rebase`,
# `push`, etc. The arguments passed to log.
#
# Place it somewhere on Your `$PATH` and execute by the `git fetch-log`
# command.
#
#                               EXAMPLE OUTPUT
# ============================================================================
#
# ==== branch [behind 1]
#
# > commit 652b883 (origin/branch)
# | Author: BimbaLaszlo <bimbalaszlo@gmail.com>
# | Date:   2016-03-10 09:11:11 +0100
# |
# |     Commit on remote
# |
# o commit 2304667 (branch)
#   Author: BimbaLaszlo <bimbalaszlo@gmail.com>
#   Date:   2015-08-28 13:21:13 +0200
#
#       Commit on local
#
# ==== master [ahead 1]
#
# < commit 280ccf8 (master)
# | Author: BimbaLaszlo <bimbalaszlo@gmail.com>
# | Date:   2016-03-25 21:42:55 +0100
# |
# |     Commit on local
# |
# o commit 2369465 (origin/master, origin/HEAD)
#   Author: BimbaLaszlo <bimbalaszlo@gmail.com>
#   Date:   2016-03-10 09:02:52 +0100
#
#       Commit on remote
#
# ==== test [ahead 1, behind 1]
#
# < commit 83a3161 (test)
# | Author: BimbaLaszlo <bimbalaszlo@gmail.com>
# | Date:   2016-03-25 22:50:00 +0100
# |
# |     Diverged from remote
# |
# | > commit 4aafec7 (origin/test)
# |/  Author: BimbaLaszlo <bimbalaszlo@gmail.com>
# |   Date:   2016-03-14 10:34:28 +0100
# |
# |       Pushed remote
# |
# o commit 0fccef3
#   Author: BimbaLaszlo <bimbalaszlo@gmail.com>
#   Date:   2015-09-03 10:33:39 +0200
#
#       Last common commit

  fmt='ref=%(refname:short); up=%(upstream:short); t=%(upstream:track); ts=%(upstream:trackshort);'
  git for-each-ref --shell --format="$fmt" refs/heads | \
  while read entry; do
    eval "$entry"
    if test "z$ts" != 'z' && test "z$ts" != 'z='; then
      echo -e "\n==== $ref $t\n"
      git --no-pager log --graph --left-right --decorate --abbrev-commit --date-order --boundary $@ $ref...$up
    fi
  done

你会在申请开始时这样做:

public class SomeTypeWithAnIdProperty
{
    public ObjectId Id { get; set; }
}

如果您不了解这些类型,但您对它们有所了解,例如:   - 他们都实现了某个界面或   - 他们都坐在某个名称空间或   - 您可以列出所有其他类型的白名单 然后你可以做这样的事情(再次,在你的应用程序的开始):

BsonClassMap.RegisterClassMap<SomeTypeWithAnIdProperty>(cm => cm.UnmapProperty(c => c.Id));