public void TestMapDateTime()
        {
            var value          = DateTime.UtcNow;
            var valueTruncated = value.AddTicks(-(value.Ticks % 10000));
            var bsonValue      = (BsonDateTime)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(valueTruncated, bsonValue.Value);
            var bsonDateTime = (BsonDateTime)BsonTypeMapper.MapToBsonValue(value, BsonType.DateTime);

            Assert.AreEqual(valueTruncated, bsonDateTime.Value);
        }
Ejemplo n.º 2
0
        protected override void DeleteEntity(TIdentity identity)
        {
            if (!IsValidKey(identity))
            {
                throw new ArgumentException("No valid key for entity.");
            }

            var keyMemberMap = BsonClassMap.LookupClassMap(typeof(TEntity)).IdMemberMap;
            var keyBsonType  = ((RepresentationSerializationOptions)keyMemberMap.SerializationOptions).Representation;

            BaseCollection.Remove(Query.EQ(keyMemberMap.ElementName, BsonTypeMapper.MapToBsonValue(identity, keyBsonType)));
        }
Ejemplo n.º 3
0
        public void TestBsonTypeMapperMapToBsonValue()
        {
            var document1 = (BsonDocument)BsonTypeMapper.MapToBsonValue(_dictionary, BsonType.Document);
            var document2 = (BsonDocument)BsonTypeMapper.MapToBsonValue(_hashtable, BsonType.Document);
            var document3 = (BsonDocument)BsonTypeMapper.MapToBsonValue(_idictionaryNonGeneric, BsonType.Document);
            var document4 = (BsonDocument)BsonTypeMapper.MapToBsonValue(_idictionary, BsonType.Document);

            Assert.AreEqual("Dictionary<string, object>", document1["type"].AsString);
            Assert.AreEqual("Hashtable", document2["type"].AsString);
            Assert.AreEqual("IDictionary", document3["type"].AsString);
            Assert.AreEqual("IDictionary<string, object>", document4["type"].AsString);
        }
        public BsonValue GetBsonIdValueFromEntity(object entity)
        {
            var entityType   = entity.GetType();
            var propertyInfo = default(PropertyInfo);

            if (!_TypeToIdPropertyInfoMappings.TryGetValue(entityType, out propertyInfo))
            {
                lock (SyncObject)
                {
                    if (!_TypeToIdPropertyInfoMappings.ContainsKey(entityType))
                    {
                        var entityPi = default(PropertyInfo);

                        foreach (var pi in entityType.GetProperties())
                        {
                            if (pi.PropertyType == typeof(BsonIdAttribute) ||
                                pi.CustomAttributes.SingleOrDefault(p2 => p2.AttributeType == typeof(BsonIdAttribute)) != null)
                            {
                                entityPi = pi;
                                break;
                            }
                        }

                        if (entityPi == null)
                        {
                            foreach (var pi in entityType.GetProperties())
                            {
                                if (pi.Name.ToUpper().EndsWith("ID"))
                                {
                                    entityPi = pi;
                                    break;
                                }
                            }
                        }

                        if (entityPi != null)
                        {
                            _TypeToIdPropertyInfoMappings[entityType] = entityPi;
                        }
                    }
                }
            }

            if (propertyInfo == null && !_TypeToIdPropertyInfoMappings.TryGetValue(entityType, out propertyInfo))
            {
                throw new NotSupportedException(string.Format("Unable to find BsonIdAttribute on type '{0}'. Add new IMongoDbOverridables.GetBsonIdValueFromEntity implemetation to handle this scenario.", entityType));
            }

            var idValue   = propertyInfo.GetValue(entity);
            var bsonValue = BsonTypeMapper.MapToBsonValue(idValue);

            return(bsonValue);
        }
Ejemplo n.º 5
0
        public void TestMapGuid()
        {
            var value     = Guid.NewGuid();
            var bsonValue = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value);

            Assert.IsTrue(value.ToByteArray().SequenceEqual(bsonValue.Bytes));
            Assert.AreEqual(BsonBinarySubType.UuidLegacy, bsonValue.SubType);
            var bsonBinary = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value, BsonType.Binary);

            Assert.IsTrue(value.ToByteArray().SequenceEqual(bsonBinary.Bytes));
            Assert.AreEqual(BsonBinarySubType.UuidLegacy, bsonBinary.SubType);
        }
Ejemplo n.º 6
0
        public void TestMapRegex()
        {
            var value     = new Regex("pattern");
            var bsonValue = (BsonRegularExpression)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual("pattern", bsonValue.Pattern);
            Assert.AreEqual("", bsonValue.Options);
            var bsonRegularExpression = (BsonRegularExpression)BsonTypeMapper.MapToBsonValue(value, BsonType.RegularExpression);

            Assert.AreEqual("pattern", bsonRegularExpression.Pattern);
            Assert.AreEqual("", bsonRegularExpression.Options);
        }
Ejemplo n.º 7
0
        public void TestMapBsonUndefined()
        {
            var value     = BsonUndefined.Value;
            var bsonValue = (BsonUndefined)BsonTypeMapper.MapToBsonValue(value);

            Assert.Same(value, bsonValue);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.False(bsonBoolean.Value);
            var bsonUndefined = (BsonUndefined)BsonTypeMapper.MapToBsonValue(value, BsonType.Undefined);

            Assert.Same(value, bsonUndefined);
        }
Ejemplo n.º 8
0
        public void TestMapBsonMinKey()
        {
            var value     = BsonMinKey.Value;
            var bsonValue = (BsonMinKey)BsonTypeMapper.MapToBsonValue(value);

            Assert.Same(value, bsonValue);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.True(bsonBoolean.Value);
            var bsonMinKey = (BsonMinKey)BsonTypeMapper.MapToBsonValue(value, BsonType.MinKey);

            Assert.Same(value, bsonMinKey);
        }
        public void TestMapBsonDocument()
        {
            var value     = new BsonDocument();
            var bsonValue = (BsonDocument)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreSame(value, bsonValue);
            var bsonArray = (BsonArray)BsonTypeMapper.MapToBsonValue(value, BsonType.Array);

            Assert.AreEqual(0, bsonArray.Count);
            var bsonDocument = (BsonDocument)BsonTypeMapper.MapToBsonValue(value, BsonType.Document);

            Assert.AreSame(value, bsonDocument);
        }
        public static BsonDocument ToBsonDoc(SiaqodbDocument cobj)
        {
            var doc = new BsonDocument();

            doc["_id"]  = cobj.Key;
            doc["_rev"] = BsonTypeMapper.MapToBsonValue(cobj.Version);
            doc["doc"]  = cobj.Content;
            foreach (string tagName in cobj.Tags.Keys)
            {
                doc[tagName] = BsonTypeMapper.MapToBsonValue(cobj.Tags[tagName]);
            }
            return(doc);
        }
Ejemplo n.º 11
0
        public void TestMapDecimal128()
        {
            var value     = (Decimal128)1.2M;
            var bsonValue = (BsonDecimal128)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue(value, BsonType.Decimal128);

            Assert.Equal(value, bsonDecimal128.Value);
        }
        public void TestMapSByteEnum()
        {
            var value     = SByteEnum.V;
            var bsonValue = (BsonInt32)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal((int)(sbyte)value, bsonValue.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);

            Assert.Equal((int)(sbyte)value, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.Equal((long)(sbyte)value, bsonInt64.Value);
        }
        protected override void DeleteItem(T entity)
        {
            TKey pkValue;

            GetPrimaryKey(entity, out pkValue);

            if (IsValidKey(pkValue))
            {
                var keyMemberMap = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap;
                var keyBsonType  = ((RepresentationSerializationOptions)keyMemberMap.SerializationOptions).Representation;
                BaseCollection().Remove(Query.EQ(keyMemberMap.ElementName, BsonTypeMapper.MapToBsonValue(pkValue, keyBsonType)));
            }
        }
Ejemplo n.º 14
0
        public void TestMapSingle()
        {
            var value     = (float)1.2;
            var bsonValue = (BsonDouble)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.AreEqual(true, bsonBoolean.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.AreEqual(value, bsonDouble.Value);
        }
Ejemplo n.º 15
0
        public void TestMapBsonNull()
        {
            var value     = BsonNull.Value;
            var bsonValue = (BsonNull)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreSame(value, bsonValue);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.AreEqual(false, bsonBoolean.Value);
            var bsonNull = (BsonNull)BsonTypeMapper.MapToBsonValue(value, BsonType.Null);

            Assert.AreSame(value, bsonNull);
        }
Ejemplo n.º 16
0
        public void TestMapUInt16Enum()
        {
            var value     = UInt16Enum.V;
            var bsonValue = (BsonInt32)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual((int)(ushort)value, bsonValue.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);

            Assert.AreEqual((int)(ushort)value, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.AreEqual((long)(ushort)value, bsonInt64.Value);
        }
Ejemplo n.º 17
0
        public void TestMapBsonJavaScript()
        {
            var value     = new BsonJavaScript("code");
            var bsonValue = (BsonJavaScript)BsonTypeMapper.MapToBsonValue(value);

            Assert.Same(value, bsonValue);
            var bsonJavaScript = (BsonJavaScript)BsonTypeMapper.MapToBsonValue(value, BsonType.JavaScript);

            Assert.Same(value, bsonJavaScript);
            var bsonJavaScriptWithScope = (BsonJavaScriptWithScope)BsonTypeMapper.MapToBsonValue(value, BsonType.JavaScriptWithScope);

            Assert.Equal(value.Code, bsonJavaScriptWithScope.Code);
            Assert.Equal(new BsonDocument(), bsonJavaScriptWithScope.Scope);
        }
Ejemplo n.º 18
0
        public void TestMapString()
        {
            var value     = "hello";
            var bsonValue = (BsonString)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue("1", BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDateTime = (BsonDateTime)BsonTypeMapper.MapToBsonValue("2010-01-02", BsonType.DateTime);

            Assert.Equal(new DateTime(2010, 1, 2), bsonDateTime.ToUniversalTime());
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Decimal128);

            Assert.Equal((Decimal128)1.2M, bsonDecimal128.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Double);

            Assert.Equal(1.2, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue("1", BsonType.Int32);

            Assert.Equal(1, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue("1", BsonType.Int64);

            Assert.Equal(1L, bsonInt64.Value);
            var bsonJavaScript = (BsonJavaScript)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScript);

            Assert.Equal("code", bsonJavaScript.Code);
            var bsonJavaScriptWithScope = (BsonJavaScriptWithScope)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScriptWithScope);

            Assert.Equal("code", bsonJavaScriptWithScope.Code);
            Assert.Equal(0, bsonJavaScriptWithScope.Scope.ElementCount);
            var objectId     = ObjectId.GenerateNewId();
            var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(objectId.ToString(), BsonType.ObjectId);

            Assert.Equal(objectId, bsonObjectId.Value);
            var bsonRegularExpression = (BsonRegularExpression)BsonTypeMapper.MapToBsonValue(new Regex("pattern"), BsonType.RegularExpression);

            Assert.Equal("pattern", bsonRegularExpression.Pattern);
            Assert.Equal("", bsonRegularExpression.Options);
            var bsonString = (BsonString)BsonTypeMapper.MapToBsonValue(value, BsonType.String);

            Assert.Equal(value, bsonString.Value);
            var bsonSymbol = (BsonSymbol)BsonTypeMapper.MapToBsonValue("symbol", BsonType.Symbol);

            Assert.Same(BsonSymbolTable.Lookup("symbol"), bsonSymbol);
            var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue("1", BsonType.Timestamp);

            Assert.Equal(1L, bsonTimestamp.Value);
        }
Ejemplo n.º 19
0
        public void TestMapByteArray()
        {
            var value     = ObjectId.GenerateNewId().ToByteArray();
            var bsonValue = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreSame(value, bsonValue.Bytes);
            Assert.AreEqual(BsonBinarySubType.Binary, bsonValue.SubType);
            var bsonBinary = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value, BsonType.Binary);

            Assert.AreSame(value, bsonBinary.Bytes);
            Assert.AreEqual(BsonBinarySubType.Binary, bsonBinary.SubType);
            var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(value, BsonType.ObjectId);

            Assert.IsTrue(value.SequenceEqual(bsonObjectId.ToByteArray()));
        }
        public WriteConcernResult ModifyAll <TEntity>(
            ICommandRepository commandRepository,
            ISpecificationQueryStrategy <TEntity> specificationStrategy,
            WriteConcern writeConcern,
            params MongoUpdateItem <TEntity>[] updateItems) where TEntity : class
        {
            if (writeConcern == null)
            {
                throw new ArgumentNullException("writeConcern", "writeConcern is null.");
            }

            if (specificationStrategy == null)
            {
                throw new ArgumentNullException("predicate", "predicate is null.");
            }

            if (updateItems == null)
            {
                throw new ArgumentNullException("mongoUpdate", "mongoUpdate is null.");
            }

            var mongoDatabase = commandRepository.ObjectContext as MongoDatabase;

            if (mongoDatabase == null)
            {
                throw new NotSupportedException("Load can only be used with a DbContext");
            }

            var updateBuilder = new UpdateBuilder();

            foreach (var item in updateItems)
            {
                var value = BsonTypeMapper.MapToBsonValue(item.Value);
                updateBuilder.Set(item.Key, value);
            }

            var collection = mongoDatabase.GetCollection <TEntity>(typeof(TEntity).FullName);
            var query      = collection.AsQueryable().AddQueryStrategy(specificationStrategy);
            var mongoQuery = ((MongoQueryable <TEntity>)query).GetMongoQuery();

            var result = collection.Update(mongoQuery, updateBuilder, UpdateFlags.Multi, writeConcern);

            var modifyAllEvent = new MongoDbEntityModifedAllEvent <TEntity>(commandRepository, specificationStrategy, updateBuilder, writeConcern);

            commandRepository.RaiseEvent(modifyAllEvent);

            return(result);
        }
Ejemplo n.º 21
0
        public static KeyValuePair <string, BsonValue> GetMongoProperty(T entity, string propertyName)
        {
            var value          = typeof(T).GetProperty(propertyName).GetValue(entity);
            var memberMap      = BsonClassMap.LookupClassMap(typeof(T)).GetMemberMap(propertyName);
            var memberBsonType = GetBsonType(value, memberMap);

            // some "non-string types are mapped to string"
            if (memberBsonType == BsonType.String)
            {
                value = value.ToString();
            }

            var bsonPropertyValue = BsonTypeMapper.MapToBsonValue(value, memberBsonType);

            return(new KeyValuePair <string, BsonValue>(propertyName, bsonPropertyValue));
        }
        protected override T GetQuery(TKey key, IFetchStrategy <T> fetchStrategy)
        {
            var keyBsonType   = ((StringSerializer)BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.GetSerializer()).Representation;
            var keyMemberName = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.MemberName;

            if (IsValidKey(key))
            {
                var keyBsonValue = BsonTypeMapper.MapToBsonValue(key, keyBsonType);
                var filter       = Builders <T> .Filter.Eq(keyMemberName, keyBsonValue);

                return(BaseCollection().Find(filter).FirstOrDefault());
            }
            else
            {
                return(default(T));
            }
        }
Ejemplo n.º 23
0
        public void TestMapUInt32()
        {
            var value     = (uint)1;
            var bsonValue = (BsonInt64)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.AreEqual(true, bsonBoolean.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.AreEqual(value, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);

            Assert.AreEqual(value, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.AreEqual(value, bsonInt64.Value);
        }
Ejemplo n.º 24
0
        public void TestMapUInt64()
        {
            var value     = (ulong)1;
            var bsonValue = (BsonInt64)BsonTypeMapper.MapToBsonValue(value);

            Assert.AreEqual(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.AreEqual(true, bsonBoolean.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.AreEqual(value, bsonDouble.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.AreEqual(value, bsonInt64.Value);
            var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue(value, BsonType.Timestamp);

            Assert.AreEqual(value, bsonTimestamp.Value);
        }
Ejemplo n.º 25
0
        public T Load(IDictionary <string, object> @params)
        {
            // build up the query
            IMongoQuery[] q   = new IMongoQuery[@params.Keys.Count];
            int           idx = 0;

            foreach (var de in @params)
            {
                // MongoDb maps 'Id' to '_id'
                string key = de.Key;
                // ugly fix
                if (key == "Id")
                {
                    key = "_id";
                }
                q[idx++] = Query.EQ(key, BsonTypeMapper.MapToBsonValue(de.Value));
            }
            var mongoQ = Query.And(q);
            var result = Collecton.FindOneAs <T>(mongoQ);

            return(result);
        }
Ejemplo n.º 26
0
        public void TestMapChar()
        {
            var value     = (char)1;
            var bsonValue = (BsonInt32)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue(value, BsonType.Decimal128);

            Assert.Equal((Decimal128)1M, bsonDecimal128.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.Equal(1.0, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);

            Assert.Equal(1, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.Equal(1L, bsonInt64.Value);
        }
Ejemplo n.º 27
0
        public void TestMapUInt16()
        {
            var value     = (ushort)1;
            var bsonValue = (BsonInt32)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue(value, BsonType.Decimal128);

            Assert.Equal(value, bsonDecimal128.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.Equal(value, bsonDouble.Value);
            var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue(value, BsonType.Int32);

            Assert.Equal(value, bsonInt32.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.Equal(value, bsonInt64.Value);
        }
Ejemplo n.º 28
0
        public void TestMapInt64()
        {
            var value     = 1L;
            var bsonValue = (BsonInt64)BsonTypeMapper.MapToBsonValue(value);

            Assert.Equal(value, bsonValue.Value);
            var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue(value, BsonType.Boolean);

            Assert.Equal(true, bsonBoolean.Value);
            var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue(value, BsonType.Decimal128);

            Assert.Equal(value, bsonDecimal128.Value);
            var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue(value, BsonType.Double);

            Assert.Equal(value, bsonDouble.Value);
            var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue(value, BsonType.Int64);

            Assert.Equal(value, bsonInt64.Value);
            var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue(value, BsonType.Timestamp);

            Assert.Equal(value, bsonTimestamp.Value);
        }
        public void TestMapGuid(
            [ClassValues(typeof(GuidModeValues))] GuidMode mode)
        {
            mode.Set();

#pragma warning disable 618
            var value = Guid.NewGuid();
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 && BsonDefaults.GuidRepresentation != GuidRepresentation.Unspecified)
            {
                var               bsonValue = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value);
                byte[]            expectedBytes;
                BsonBinarySubType expectedSubType;
                var               guidRepresentation = BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 ? BsonDefaults.GuidRepresentation : GuidRepresentation.Unspecified;
                if (guidRepresentation == GuidRepresentation.Unspecified)
                {
                    expectedBytes   = GuidConverter.ToBytes(value, GuidRepresentation.Standard);
                    expectedSubType = BsonBinarySubType.UuidStandard;
                }
                else
                {
                    expectedBytes   = GuidConverter.ToBytes(value, guidRepresentation);
                    expectedSubType = GuidConverter.GetSubType(guidRepresentation);
                }
                Assert.True(expectedBytes.SequenceEqual(bsonValue.Bytes));
                Assert.Equal(expectedSubType, bsonValue.SubType);
                var bsonBinary = (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value, BsonType.Binary);
                Assert.True(expectedBytes.SequenceEqual(bsonBinary.Bytes));
                Assert.Equal(expectedSubType, bsonBinary.SubType);
            }
            else
            {
                var exception = Record.Exception(() => (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value));
                exception.Should().BeOfType <InvalidOperationException>();
                exception = Record.Exception(() => (BsonBinaryData)BsonTypeMapper.MapToBsonValue(value, BsonType.Binary));
                exception.Should().BeOfType <InvalidOperationException>();
            }
#pragma warning restore 618
        }
        /// <summary>
        /// Deletes many to many relation record
        /// </summary>
        /// <param name="relationId"></param>
        /// <param name="originId"></param>
        /// <param name="targetId"></param>
        public void DeleteManyToManyRecord(Guid relationId, Guid originId, Guid targetId)
        {
            var entityRepository = new MongoEntityRepository();
            var relation         = Read(relationId);
            var originEntity     = entityRepository.Read(relation.OriginEntityId);
            var originField      = originEntity.Fields.Single(x => x.Id == relation.OriginFieldId);
            var targetEntity     = entityRepository.Read(relation.TargetEntityId);
            var targetField      = targetEntity.Fields.Single(x => x.Id == relation.TargetFieldId);

            var originColletion = MongoStaticContext.Context.GetBsonCollection("rec_" + originEntity.Name);
            var originFieldName = originField.Name;

            if (originFieldName == "id")
            {
                originFieldName = "_id";
            }
            var          originRecords      = originColletion.Find(Query.EQ(originFieldName, originId)).ToList();
            var          originRecordsCount = originRecords.Count();
            BsonDocument originRecord       = null;

            if (originRecordsCount == 0)
            {
                throw new StorageException("There are no record with specified origin id.");
            }
            else if (originRecordsCount > 1)
            {
                throw new StorageException("There are more than 1 record with same origin id.");
            }
            else
            {
                originRecord = originRecords[0];
                var         targetsElementName = $"#{ relation.Name}_targets";
                BsonElement bsonElement        = null;
                try { bsonElement = originRecord.GetElement(targetsElementName); } catch { }
                if (bsonElement != null)
                {
                    var targets = BsonTypeMapper.MapToDotNetValue(bsonElement.Value) as List <object>;
                    if (targets != null && targets.Contains(targetId))
                    {
                        targets.Remove(targetId);
                        if (targets.Count == 0)
                        {
                            targets = null;
                        }
                        originRecord[targetsElementName] = BsonTypeMapper.MapToBsonValue(targets);
                    }
                }
                else
                {
                    originRecord[targetsElementName] = BsonTypeMapper.MapToBsonValue(null);
                }
            }

            var targetColletion = MongoStaticContext.Context.GetBsonCollection("rec_" + targetEntity.Name);
            var targetFieldName = targetField.Name;

            if (targetFieldName == "id")
            {
                targetFieldName = "_id";
            }
            var          targetRecords      = targetColletion.Find(Query.EQ(targetFieldName, targetId)).ToList();
            var          targetRecordsCount = targetRecords.Count();
            BsonDocument targetRecord       = null;

            if (targetRecordsCount == 0)
            {
                throw new StorageException("There are no record with specified target id.");
            }
            else if (targetRecordsCount > 1)
            {
                throw new StorageException("There are more than 1 record with same target id.");
            }
            else
            {
                targetRecord = targetRecords[0];
                var         originsElementName = $"#{ relation.Name}_origins";
                BsonElement bsonElement        = null;
                try { bsonElement = targetRecord.GetElement(originsElementName); } catch { }
                if (bsonElement != null)
                {
                    var origins = BsonTypeMapper.MapToDotNetValue(bsonElement.Value) as List <object>;
                    if (origins != null && origins.Contains(originId))
                    {
                        origins.Remove(originId);
                        if (origins.Count == 0)
                        {
                            origins = null;
                        }
                        targetRecord[originsElementName] = BsonTypeMapper.MapToBsonValue(origins);
                    }
                }
                else
                {
                    targetRecord[originsElementName] = BsonTypeMapper.MapToBsonValue(null);
                }
            }

            MongoTransaction transaction = null;

            if (!MongoStaticContext.Context.TransactionInProgress)
            {
                transaction = MongoStaticContext.Context.CreateTransaction();
            }

            try
            {
                originColletion.Save(originRecord);
                targetColletion.Save(targetRecord);

                if (transaction != null)
                {
                    transaction.Commit();
                }
            }
            catch
            {
                if (transaction != null)
                {
                    transaction.Rollback();
                }

                throw;
            }
        }