Марк Петров
Марк Петров

Reputation: 11

Can not insert entity with null as BsonId in MongoDb

I'm trying to start working with mongo db. But as i were trying to add new element with string Id = null, because it's new it gives me an error

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

        public abstract string CollectionName { get; }
    }

Whenever i try to add by running:

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

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

            return newEntity.Id;
        }

I get '0' is not a valid 24 digit hex string with each try.

Upvotes: 1

Views: 1905

Answers (1)

Clement Amarnath
Clement Amarnath

Reputation: 5466

It is giving the correct message, try with a value for Id

Please see the below code snippet from MongoDB.Bson/ObjectModel/ObjectId.cs

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

Upvotes: 1

Related Questions