【问题标题】:Can not insert entity with null as BsonId in MongoDb无法在 MongoDb 中插入具有 null 作为 BsonId 的实体
【发布时间】:2019-08-06 20:36:24
【问题描述】:

我正在尝试开始使用 mongo db。但是当我尝试使用字符串 Id = null 添加新元素时,因为它是新元素,所以它给了我一个错误

    public abstract class BaseEntity
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        public abstract string CollectionName { get; }
    }

每当我尝试通过运行添加时:

public string InsertOne(TEntity newEntity)
        {
            if(newEntity == null)
            {
                throw new ArgumentNullException(nameof(newEntity));
            }

            var collection = _mongoContext.Collection<TEntity>();
            collection.InsertOne(newEntity);

            return newEntity.Id;
        }

我每次尝试都得到 '0' 不是有效的 24 位十六进制字符串。

【问题讨论】:

    标签: c# mongodb mongodb-query


    【解决方案1】:

    它给出了正确的消息,尝试使用 Id 的值

    请看下面来自MongoDB.Bson/ObjectModel/ObjectId.cs的代码sn-p

    public static ObjectId Parse(string s)
            {
                if (s == null)
                {
                    throw new ArgumentNullException("s");
                }
    
                ObjectId objectId;
                if (TryParse(s, out objectId))
                {
                    return objectId;
                }
                else
                {
                    var message = string.Format("'{0}' is not a valid 24 digit hex string.", s);
                    throw new FormatException(message);
                }
            }
    ....
    ....
    ....
    public static bool TryParse(string s, out ObjectId objectId)
        {
            // don't throw ArgumentNullException if s is null
            if (s != null && s.Length == 24)
            {
                byte[] bytes;
                if (BsonUtils.TryParseHexString(s, out bytes))
                {
                    objectId = new ObjectId(bytes);
                    return true;
                }
            }
    
            objectId = default(ObjectId);
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多