コード例 #1
0
ファイル: BsonFieldTest.cs プロジェクト: ktaranov/LiteDB
        public void BsonField_Test()
        {
            var mapper = new BsonMapper();
            mapper.UseLowerCaseDelimiter('_');

            var obj = CreateModel();
            var doc = mapper.ToDocument(obj);

            var json = JsonSerializer.Serialize(doc, true);
            var nobj = mapper.ToObject<MyBsonFieldTestClass>(doc);

            Assert.AreEqual(doc["MY-STRING"].AsString, obj.MyString);
            Assert.AreEqual(doc["INTERNAL-PROPERTY"].AsString, obj.MyInternalPropertyNamed);
            Assert.AreEqual(doc["PRIVATE-PROPERTY"].AsString, obj.GetMyPrivatePropertyNamed());
            Assert.AreEqual(doc["PROTECTED-PROPERTY"].AsString, obj.GetMyProtectedPropertyNamed());
            Assert.AreEqual(obj.MyString, nobj.MyString);
            //Internal
            Assert.AreEqual(obj.MyInternalPropertyNamed, nobj.MyInternalPropertyNamed);
            Assert.AreEqual(obj.MyInternalPropertySerializable, nobj.MyInternalPropertySerializable);
            Assert.AreEqual(nobj.MyInternalPropertyNotSerializable,null);
            //Private
            Assert.AreEqual(obj.GetMyPrivatePropertyNamed(), nobj.GetMyPrivatePropertyNamed());
            Assert.AreEqual(obj.GetMyPrivatePropertySerializable(), nobj.GetMyPrivatePropertySerializable());
            Assert.AreEqual(nobj.GetMyPrivatePropertyNotSerializable(), null);
            //protected
            Assert.AreEqual(obj.GetMyProtectedPropertyNamed(), nobj.GetMyProtectedPropertyNamed());
            Assert.AreEqual(obj.GetMyProtectedPropertySerializable(), nobj.GetMyProtectedPropertySerializable());
            Assert.AreEqual(nobj.GetMyProtectedPropertyNotSerializable(), null);
        }
コード例 #2
0
ファイル: Database.cs プロジェクト: atst1996/Gouter
    /// <summary>
    /// データベースファイルを読み込む。
    /// </summary>
    /// <param name="filePath">ファイルパス</param>
    public void Connect(string filePath)
    {
        if (this._connection != null)
        {
            throw new InvalidOperationException();
        }

        var mapper = new BsonMapper();

        var connectionString = new ConnectionString
        {
            Collation = Collation.Binary,
            Filename  = filePath,
            ReadOnly  = false,
            Upgrade   = true,
        };
        var conn = new LiteDatabase(connectionString, mapper);

        this._mapper     = mapper;
        this._connection = conn;

        this.Context = new DbContext(this._connection);

        this.ConfigurationDatabase();

        this.IsConnected = true;
    }
コード例 #3
0
ファイル: IncludeTest.cs プロジェクト: ktaranov/LiteDB
 protected override void OnModelCreating(BsonMapper mapper)
 {
     mapper.Entity<Order>()
         .DbRef(x => x.Products, "products")
         .DbRef(x => x.ProductArray, "products")
         .DbRef(x => x.ProductColl, "products")
         .DbRef(x => x.ProductEmpty, "products")
         .DbRef(x => x.ProductsNull, "products")
         .DbRef(x => x.Customer, "customers")
         .DbRef(x => x.CustomerNull, "customers");
 }
コード例 #4
0
ファイル: MapperTest.cs プロジェクト: remcodegroot/LiteDB
        public void Mapper_Test()
        {
            var mapper = new BsonMapper();
            mapper.UseLowerCaseDelimiter('_');

            var obj = CreateModel();
            var doc = mapper.ToDocument(obj);

            var json = JsonSerializer.Serialize(doc, true);

            var nobj = mapper.ToObject<MyClass>(doc);

            // compare object to document
            Assert.AreEqual(doc["_id"].AsInt32, obj.MyId);
            Assert.AreEqual(doc["MY-STRING"].AsString, obj.MyString);
            Assert.AreEqual(doc["my_guid"].AsGuid, obj.MyGuid);

            // compare 2 objects
            Assert.AreEqual(obj.MyId, nobj.MyId);
            Assert.AreEqual(obj.MyString, nobj.MyString);
            Assert.AreEqual(obj.MyProperty, nobj.MyProperty);
            Assert.AreEqual(obj.MyGuid, nobj.MyGuid);
            Assert.AreEqual(obj.MyDateTime, nobj.MyDateTime);
            Assert.AreEqual(obj.MyDateTimeNullable, nobj.MyDateTimeNullable);
            Assert.AreEqual(obj.MyIntNullable, nobj.MyIntNullable);
            Assert.AreEqual(obj.MyEnumProp, nobj.MyEnumProp);
            Assert.AreEqual(obj.MyChar, nobj.MyChar);
            Assert.AreEqual(obj.MyByte, nobj.MyByte);
            Assert.AreEqual(obj.MyDecimal, nobj.MyDecimal);
            Assert.AreEqual(obj.MyUri, nobj.MyUri);
            Assert.AreEqual(obj.MyNameValueCollection["key-1"], nobj.MyNameValueCollection["key-1"]);
            Assert.AreEqual(obj.MyNameValueCollection["KeyNumber2"], nobj.MyNameValueCollection["KeyNumber2"]);

            // list
            Assert.AreEqual(obj.MyStringArray[0], nobj.MyStringArray[0]);
            Assert.AreEqual(obj.MyStringArray[1], nobj.MyStringArray[1]);
            Assert.AreEqual(obj.MyDict[2], nobj.MyDict[2]);

            // interfaces
            Assert.AreEqual(obj.MyInterface.Name, nobj.MyInterface.Name);
            Assert.AreEqual(obj.MyListInterface[0].Name, nobj.MyListInterface[0].Name);
            Assert.AreEqual(obj.MyIListInterface[0].Name, nobj.MyIListInterface[0].Name);

            // objects
            Assert.AreEqual(obj.MyObjectString, nobj.MyObjectString);
            Assert.AreEqual(obj.MyObjectInt, nobj.MyObjectInt);
            Assert.AreEqual((obj.MyObjectImpl as MyImpl).Name, (nobj.MyObjectImpl as MyImpl).Name);
            Assert.AreEqual(obj.MyObjectList[0], obj.MyObjectList[0]);
            Assert.AreEqual(obj.MyObjectList[1], obj.MyObjectList[1]);
            Assert.AreEqual(obj.MyObjectList[3], obj.MyObjectList[3]);

            Assert.AreEqual(nobj.MyInternalProperty, null);
        }
コード例 #5
0
 private void InitializeMapper()
 {
     lock (_mapperCache)
     {
         if (!_mapperCache.TryGetValue(this.GetType(), out _mapper))
         {
             _mapper = new BsonMapper();
             _mapperCache.Add(this.GetType(), _mapper);
             this.OnModelCreating(_mapper);
         }
     }
 }
コード例 #6
0
        public void MapInterfaces_Test()
        {
            var mapper = new BsonMapper();

            var c1 = new MyClassWithInterface { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } };
            var c2 = new MyClassWithObject { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } };
            var c3 = new MyClassWithClassName { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } };

            var bson1 = mapper.ToDocument(c1); // add _type in Impl property
            var bson2 = mapper.ToDocument(c2); // add _type in Impl property
            var bson3 = mapper.ToDocument(c3); // do not add _type in Impl property

            Assert.AreEqual("UnitTest.MapperInterfaceTest+MyClassImpl, UnitTest", bson1["Impl"].AsDocument["_type"].AsString);
            Assert.AreEqual("UnitTest.MapperInterfaceTest+MyClassImpl, UnitTest", bson2["Impl"].AsDocument["_type"].AsString);
            Assert.AreEqual(false, bson3["Impl"].AsDocument.ContainsKey("_type"));

            var k1 = mapper.ToObject<MyClassWithInterface>(bson1);
            var k2 = mapper.ToObject<MyClassWithObject>(bson2);
            var k3 = mapper.ToObject<MyClassWithClassName>(bson3);

            Assert.AreEqual(c1.Impl.Name, k1.Impl.Name);
            Assert.AreEqual((c2.Impl as MyClassImpl).Name, (k2.Impl as MyClassImpl).Name);
            Assert.AreEqual(c3.Impl.Name, k3.Impl.Name);
        }
コード例 #7
0
 public GameScannersCollection(GameDatabase database, LiteDB.BsonMapper mapper) : base(mapper, type: GameDatabaseCollection.GameScanners)
 {
     db = database;
 }
コード例 #8
0
ファイル: VirtualFieldTest.cs プロジェクト: ktaranov/LiteDB
 protected override void OnModelCreating(BsonMapper mapper)
 {
     mapper.Entity<VirtualFieldEntity>()
         .Index("name_length", (c) => c.Name.Length);
 }
コード例 #9
0
        /// <summary>
        /// Use this method to override how your class can be, by default, mapped from entity to Bson document.
        /// Returns an EntityMapper from each requested Type
        /// </summary>
        protected virtual EntityMapper BuildEntityMapper(Type type)
        {
            var mapper = new EntityMapper
            {
                Members = new List <MemberMapper>(),
                ForType = type
            };

            var idAttr     = typeof(BsonIdAttribute);
            var ignoreAttr = typeof(BsonIgnoreAttribute);
            var fieldAttr  = typeof(BsonFieldAttribute);
            var indexAttr  = typeof(BsonIndexAttribute);
            var dbrefAttr  = typeof(BsonRefAttribute);

            foreach (var memberInfo in this.GetTypeMembers(type))
            {
                // checks [BsonIgnore]
                if (memberInfo.IsDefined(ignoreAttr, true))
                {
                    continue;
                }

                // checks field name conversion
                var name = this.ResolveFieldName(memberInfo.Name);

                // checks if is _id
                if (this.IsMemberId(type, memberInfo))
                {
                    name = "_id";
                }

                // check if property has [BsonField]
                var field = (BsonFieldAttribute)memberInfo.GetCustomAttributes(fieldAttr, false).FirstOrDefault();

                // check if property has [BsonField] with a custom field name
                if (field != null && field.Name != null)
                {
                    name = field.Name;
                }

                // test if field name is OK (avoid to check in all instances) - do not test internal classes, like DbRef
                if (BsonDocument.IsValidFieldName(name) == false)
                {
                    throw LiteException.InvalidFormat(memberInfo.Name, name);
                }

                // create getter/setter function
                var getter = Reflection.CreateGenericGetter(type, memberInfo);
                var setter = Reflection.CreateGenericSetter(type, memberInfo);

                // check if property has [BsonId] to get with was setted AutoId = true
                var autoId = (BsonIdAttribute)memberInfo.GetCustomAttributes(idAttr, false).FirstOrDefault();

                // checks if this property has [BsonIndex]
                var index = (BsonIndexAttribute)memberInfo.GetCustomAttributes(indexAttr, false).FirstOrDefault();

                // get data type
                var dataType = memberInfo is PropertyInfo ?
                               (memberInfo as PropertyInfo).PropertyType :
                               (memberInfo as FieldInfo).FieldType;

                // check if datatype is list/array
                var isList = Reflection.IsList(dataType);

                // create a property mapper
                var member = new MemberMapper
                {
                    AutoId         = autoId == null ? true : autoId.AutoId,
                    FieldName      = name,
                    MemberName     = memberInfo.Name,
                    DataType       = dataType,
                    IsUnique       = index == null ? false : index.Unique,
                    IsList         = isList,
                    UnderlyingType = isList ? Reflection.GetListItemType(dataType) : dataType,
                    Getter         = getter,
                    Setter         = setter
                };

                // check if property has [BsonRef]
                var dbRef = (BsonRefAttribute)memberInfo.GetCustomAttributes(dbrefAttr, false).FirstOrDefault();

                if (dbRef != null && memberInfo is PropertyInfo)
                {
                    BsonMapper.RegisterDbRef(this, member, dbRef.Collection);
                }

                // support callback to user modify member mapper
                if (this.ResolveMember != null)
                {
                    this.ResolveMember(type, memberInfo, member);
                }

                // test if has name and there is no duplicate field
                if (member.FieldName != null && mapper.Members.Any(x => x.FieldName == name) == false)
                {
                    mapper.Members.Add(member);
                }
            }

            return(mapper);
        }
コード例 #10
0
 /// <summary>
 /// Starts LiteDB database using a connection string for file system database
 /// </summary>
 public LiteDatabase(string connectionString, BsonMapper mapper = null)
     : this(new ConnectionString(connectionString), mapper)
 {
 }
コード例 #11
0
        /// <summary>
        /// Register a property as a DbRef - implement a custom Serialize/Deserialize actions to convert entity to $id, $ref only
        /// </summary>
        private static void RegisterDbRefItem(BsonMapper mapper, MemberMapper member, ITypeNameBinder typeNameBinder, string collection)
        {
            // get entity
            var entity = mapper.GetEntityMapper(member.DataType);

            member.Serialize = (obj, m) =>
            {
                // supports null values when "SerializeNullValues = true"
                if (obj == null)
                {
                    return(BsonValue.Null);
                }

                var idField = entity.Id;

                // #768 if using DbRef with interface with no ID mapped
                if (idField == null)
                {
                    throw new LiteException(0, "There is no _id field mapped in your type: " + member.DataType.FullName);
                }

                var id = idField.Getter(obj);

                var bsonDocument = new BsonDocument
                {
                    ["$id"]  = m.Serialize(id.GetType(), id, 0),
                    ["$ref"] = collection
                };

                if (member.DataType != obj.GetType())
                {
                    bsonDocument["$type"] = typeNameBinder.GetName(obj.GetType());
                }

                return(bsonDocument);
            };

            member.Deserialize = (bson, m) =>
            {
                // if not a document (maybe BsonValue.null) returns null
                if (bson == null || bson.IsDocument == false)
                {
                    return(null);
                }

                var doc      = bson.AsDocument;
                var idRef    = doc["$id"];
                var missing  = doc["$missing"] == true;
                var included = doc.ContainsKey("$ref") == false;

                if (missing)
                {
                    return(null);
                }

                if (included)
                {
                    doc["_id"] = idRef;

                    return(m.Deserialize(entity.ForType, doc));
                }
                else
                {
                    return(m.Deserialize(entity.ForType,
                                         doc.ContainsKey("$type") ?
                                         new BsonDocument {
                        ["_id"] = idRef, ["_type"] = bson["$type"]
                    } :
                                         new BsonDocument {
                        ["_id"] = idRef
                    }));                                           // if has $id, deserialize object using only _id object
                }
            };
        }
コード例 #12
0
ファイル: LiteCollection.cs プロジェクト: zhb123456789/LiteDB
        internal LiteCollection(string name, BsonAutoId autoId, Lazy <ILiteEngine> engine, BsonMapper mapper)
        {
            _collection = name ?? mapper.ResolveCollectionName(typeof(T));
            _engine     = engine;
            _mapper     = mapper;
            _includes   = new List <BsonExpression>();

            // if strong typed collection, get _id member mapped (if exists)
            if (typeof(T) == typeof(BsonDocument))
            {
                _id     = null;
                _autoId = autoId;
            }
            else
            {
                var entity = mapper.GetEntityMapper(typeof(T));
                _id = entity.Id;

                if (_id != null && _id.AutoId)
                {
                    _autoId =
                        _id.DataType == typeof(Int32) || _id.DataType == typeof(Int32?) ? BsonAutoId.Int32 :
                        _id.DataType == typeof(Int64) || _id.DataType == typeof(Int64?) ? BsonAutoId.Int64 :
                        _id.DataType == typeof(Guid) || _id.DataType == typeof(Guid?) ? BsonAutoId.Guid :
                        BsonAutoId.ObjectId;
                }
            }
        }
コード例 #13
0
 public static void MapLiteDbEntities(LiteDB.BsonMapper mapper)
 {
     mapper.Entity <CompletionStatus>().Id(a => a.Id, false);
 }
コード例 #14
0
 public CompletionStatusesCollection(GameDatabase database, LiteDB.BsonMapper mapper) : base(mapper, type: GameDatabaseCollection.CompletionStatuses)
 {
     db = database;
 }
コード例 #15
0
 public LinqExpressionVisitor(BsonMapper mapper)
 {
     _mapper = mapper;
 }
コード例 #16
0
ファイル: LiteDatabase.cs プロジェクト: makandok/LiteDB
        /// <summary>
        /// Starts LiteDB database using a custom IDiskService with all parameters avaiable
        /// </summary>
        /// <param name="diskService">Custom implementation of persist data layer</param>
        /// <param name="mapper">Instance of BsonMapper that map poco classes to document</param>
        /// <param name="password">Password to encrypt you datafile</param>
        /// <param name="timeout">Locker timeout for concurrent access</param>
        /// <param name="autocommit">If auto commit after any write operation</param>
        /// <param name="cacheSize">Max memory pages used before flush data in Journal file (when avaiable)</param>
        /// <param name="log">Custom log implementation</param>
        public LiteDatabase(IDiskService diskService, BsonMapper mapper = null, string password = null, TimeSpan?timeout = null, bool autocommit = true, int cacheSize = 5000, Logger log = null)
        {
            _mapper = mapper ?? BsonMapper.Global;

            _engine = new LazyLoad <LiteEngine>(() => new LiteEngine(diskService, password: password, timeout: timeout, autocommit: autocommit, cacheSize: cacheSize, log: _log));
        }
コード例 #17
0
ファイル: LiteDatabase.cs プロジェクト: makandok/LiteDB
        /// <summary>
        /// Starts LiteDB database using a Stream disk
        /// </summary>
        public LiteDatabase(Stream stream, BsonMapper mapper = null, string password = null)
        {
            _mapper = mapper ?? BsonMapper.Global;

            _engine = new LazyLoad <LiteEngine>(() => new LiteEngine(new StreamDiskService(stream), password: password, log: _log));
        }
コード例 #18
0
ファイル: LiteDatabase.cs プロジェクト: yuyixiaoxiang/LiteDB
 /// <summary>
 /// Start LiteDB database using a pre-exiting engine. When LiteDatabase instance dispose engine instance will be disposed too
 /// </summary>
 public LiteDatabase(ILiteEngine engine, BsonMapper mapper = null, bool disposeOnClose = true)
 {
     _engine         = engine ?? throw new ArgumentNullException(nameof(engine));
     _mapper         = mapper ?? BsonMapper.Global;
     _disposeOnClose = disposeOnClose;
 }
コード例 #19
0
ファイル: EntityBuilder.cs プロジェクト: mercan01/LiteDB
 internal EntityBuilder(BsonMapper mapper)
 {
     _mapper = mapper;
     _entity = mapper.GetEntityMapper(typeof(T));
 }
コード例 #20
0
 public TorLiteDatabase(string connectionString, BsonMapper mapper = null)
     : base(connectionString, mapper)
 {
 }
コード例 #21
0
 public TorLiteDatabase(Stream stream, BsonMapper mapper = null)
     : base(stream, mapper)
 {
 }
コード例 #22
0
ファイル: DatabaseConnection.cs プロジェクト: Xicy/HairDress
        protected override void OnModelCreating(BsonMapper mapper)
        {
            mapper.Entity<Operation2Person>()
                .Id(x => x.ID)
                .Ignore(x => x.TotalCost)
                .Index(x => x.ID)
                .DbRef(x => x.Operations, TableOperation);

            mapper.Entity<Person>()
                .Id(x => x.ID)
                .Index(x => x.ID)
                .Index(x => x.Phones)
                .Index(x => x.Emails)
                .DbRef(x => x.Phones, TablePhone)
                .DbRef(x => x.Addresses, TableAddress)
                .DbRef(x => x.Emails, TableEmail)
                .DbRef(x => x.OperationsList, TableOperation2Person);
        }
コード例 #23
0
        /// <summary>
        /// Use this method to override how your class can be, by default, mapped from entity to Bson document.
        /// Returns an EntityMapper from each requested Type
        /// </summary>
        protected virtual EntityMapper BuildEntityMapper(Type type)
        {
            var mapper = new EntityMapper(type);

            var idAttr     = typeof(BsonIdAttribute);
            var ignoreAttr = typeof(BsonIgnoreAttribute);
            var fieldAttr  = typeof(BsonFieldAttribute);
            var dbrefAttr  = typeof(BsonRefAttribute);

            var members = this.GetTypeMembers(type);
            var id      = this.GetIdMember(members);

            foreach (var memberInfo in members)
            {
                // checks [BsonIgnore]
                if (CustomAttributeExtensions.IsDefined(memberInfo, ignoreAttr, true))
                {
                    continue;
                }

                // checks field name conversion
                var name = this.ResolveFieldName(memberInfo.Name);

                // check if property has [BsonField]
                var field = (BsonFieldAttribute)CustomAttributeExtensions.GetCustomAttributes(memberInfo, fieldAttr, true).FirstOrDefault();

                // check if property has [BsonField] with a custom field name
                if (field != null && field.Name != null)
                {
                    name = field.Name;
                }

                // checks if memberInfo is id field
                if (memberInfo == id)
                {
                    name = "_id";
                }

                // create getter/setter function
                var getter = Reflection.CreateGenericGetter(type, memberInfo);
                var setter = Reflection.CreateGenericSetter(type, memberInfo);

                // check if property has [BsonId] to get with was setted AutoId = true
                var autoId = (BsonIdAttribute)CustomAttributeExtensions.GetCustomAttributes(memberInfo, idAttr, true).FirstOrDefault();

                // get data type
                var dataType = memberInfo is PropertyInfo ?
                               (memberInfo as PropertyInfo).PropertyType :
                               (memberInfo as FieldInfo).FieldType;

                // check if datatype is list/array
                var isEnumerable = Reflection.IsEnumerable(dataType);

                // create a property mapper
                var member = new MemberMapper
                {
                    AutoId         = autoId == null ? true : autoId.AutoId,
                    FieldName      = name,
                    MemberName     = memberInfo.Name,
                    DataType       = dataType,
                    IsEnumerable   = isEnumerable,
                    UnderlyingType = isEnumerable ? Reflection.GetListItemType(dataType) : dataType,
                    Getter         = getter,
                    Setter         = setter
                };

                // check if property has [BsonRef]
                var dbRef = (BsonRefAttribute)CustomAttributeExtensions.GetCustomAttributes(memberInfo, dbrefAttr, false).FirstOrDefault();

                if (dbRef != null && memberInfo is PropertyInfo)
                {
                    BsonMapper.RegisterDbRef(this, member, _typeNameBinder, dbRef.Collection ?? this.ResolveCollectionName((memberInfo as PropertyInfo).PropertyType));
                }

                // support callback to user modify member mapper
                this.ResolveMember?.Invoke(type, memberInfo, member);

                // test if has name and there is no duplicate field
                if (member.FieldName != null && mapper.Members.Any(x => x.FieldName.Equals(name, StringComparison.OrdinalIgnoreCase)) == false)
                {
                    mapper.Members.Add(member);
                }
            }

            return(mapper);
        }
コード例 #24
0
        /// <summary>
        /// Register a property as a DbRefList - implement a custom Serialize/Deserialize actions to convert entity to $id, $ref only
        /// </summary>
        private static void RegisterDbRefList(BsonMapper mapper, MemberMapper member, string collection)
        {
            // get entity from list item type
            var entity = mapper.GetEntityMapper(member.UnderlyingType);

            member.Serialize = (list, m) =>
            {
                // supports null values when "SerializeNullValues = true"
                if (list == null)
                {
                    return(BsonValue.Null);
                }

                var result  = new BsonArray();
                var idField = entity.Id;

                foreach (var item in (IEnumerable)list)
                {
                    if (item == null)
                    {
                        continue;
                    }

                    var id = idField.Getter(item);

                    result.Add(new BsonDocument
                    {
                        { "$id", m.Serialize(id.GetType(), id, 0) },
                        { "$ref", collection }
                    });
                }

                return(result);
            };

            member.Deserialize = (bson, m) =>
            {
                var array = bson.AsArray;

                if (array.Count == 0)
                {
                    return(m.Deserialize(member.DataType, array));
                }

                var hasIdRef = array[0].AsDocument == null || array[0].AsDocument["$id"].IsNull;

                if (hasIdRef)
                {
                    // if no $id, deserialize as full (was loaded via Include)
                    return(m.Deserialize(member.DataType, array));
                }
                else
                {
                    // copy array changing $id to _id
                    var arr = new BsonArray();

                    foreach (var item in array)
                    {
                        arr.Add(new BsonDocument {
                            { "_id", item.AsDocument["$id"] }
                        });
                    }

                    return(m.Deserialize(member.DataType, arr));
                }
            };
        }
コード例 #25
0
        /// <summary>
        /// Register a property as a DbRefList - implement a custom Serialize/Deserialize actions to convert entity to $id, $ref only
        /// </summary>
        private static void RegisterDbRefList(BsonMapper mapper, MemberMapper member, ITypeNameBinder typeNameBinder, string collection)
        {
            // get entity from list item type
            var entity = mapper.GetEntityMapper(member.UnderlyingType);

            member.Serialize = (list, m) =>
            {
                // supports null values when "SerializeNullValues = true"
                if (list == null)
                {
                    return(BsonValue.Null);
                }

                var result  = new BsonArray();
                var idField = entity.Id;

                foreach (var item in (IEnumerable)list)
                {
                    if (item == null)
                    {
                        continue;
                    }

                    var id = idField.Getter(item);

                    var bsonDocument = new BsonDocument
                    {
                        ["$id"]  = m.Serialize(id.GetType(), id, 0),
                        ["$ref"] = collection
                    };

                    if (member.UnderlyingType != item.GetType())
                    {
                        bsonDocument["$type"] = typeNameBinder.GetName(item.GetType());
                    }

                    result.Add(bsonDocument);
                }

                return(result);
            };

            member.Deserialize = (bson, m) =>
            {
                if (bson.IsArray == false)
                {
                    return(null);
                }

                var array = bson.AsArray;

                if (array.Count == 0)
                {
                    return(m.Deserialize(member.DataType, array));
                }

                // copy array changing $id to _id
                var result = new BsonArray();

                foreach (var item in array)
                {
                    if (item.IsDocument == false)
                    {
                        continue;
                    }

                    var doc      = item.AsDocument;
                    var idRef    = doc["$id"];
                    var missing  = doc["$missing"] == true;
                    var included = doc.ContainsKey("$ref") == false;

                    // if referece document are missing, do not inlcude on output list
                    if (missing)
                    {
                        continue;
                    }

                    // if refId is null was included by "include" query, so "item" is full filled document
                    if (included)
                    {
                        item["_id"] = idRef;

                        result.Add(item);
                    }
                    else
                    {
                        var bsonDocument = new BsonDocument {
                            ["_id"] = idRef
                        };

                        if (item.AsDocument.ContainsKey("$type"))
                        {
                            bsonDocument["_type"] = item["$type"];
                        }

                        result.Add(bsonDocument);
                    }
                }

                return(m.Deserialize(member.DataType, result));
            };
        }
コード例 #26
0
ファイル: BsonMapper.cs プロジェクト: BHelfmann/LiteDB
        /// <summary>
        /// Register a property as a DbRefList - implement a custom Serialize/Deserialize actions to convert entity to $id, $ref only
        /// </summary>
        private static void RegisterDbRefList(BsonMapper mapper, MemberMapper member, string collection)
        {
            // get entity from list item type
            var entity = mapper.GetEntityMapper(member.UnderlyingType);

            member.Serialize = (list, m) =>
            {
                // supports null values when "SerializeNullValues = true"
                if (list == null)
                {
                    return(BsonValue.Null);
                }

                var result  = new BsonArray();
                var idField = entity.Id;

                foreach (var item in (IEnumerable)list)
                {
                    if (item == null)
                    {
                        continue;
                    }

                    var id = idField.Getter(item);

                    result.Add(new BsonDocument
                    {
                        { "$id", m.Serialize(id.GetType(), id, 0) },
                        { "$ref", collection }
                    });
                }

                return(result);
            };

            member.Deserialize = (bson, m) =>
            {
                var array = bson.AsArray;

                if (array.Count == 0)
                {
                    return(m.Deserialize(member.DataType, array));
                }

                // copy array changing $id to _id
                var result = new BsonArray();

                foreach (var item in array)
                {
                    var refId = item.AsDocument["$id"];

                    // if refId is null was included by "include" query, so "item" is full filled document
                    if (refId.IsNull)
                    {
                        result.Add(item);
                    }
                    else
                    {
                        result.Add(new BsonDocument {
                            { "_id", refId }
                        });
                    }
                }

                return(m.Deserialize(member.DataType, result));
            };
        }
コード例 #27
0
 public QueryVisitor(BsonMapper mapper)
 {
     _mapper = mapper;
     _type   = typeof(T);
 }
コード例 #28
0
 /// <summary>
 /// Create new instance of LiteDatabase using an external Stream source as database file
 /// </summary>
 public LiteDatabase(Stream stream, Collation collation = null, BsonMapper mapper = null)
 {
     _engine = new LiteEngine(stream, collation);
     _mapper = mapper ?? BsonMapper.Global;
 }
コード例 #29
0
ファイル: LiteDatabase.cs プロジェクト: sphinxsys/LiteDB
 /// <summary>
 /// Start LiteDB database using a pre-exiting engine. When LiteDatabase instance dispose engine instance will be disposed too
 /// </summary>
 public LiteDatabase(ILiteEngine engine, BsonMapper mapper = null)
 {
     _engine = engine;
     _mapper = mapper ?? BsonMapper.Global;
 }
コード例 #30
0
 /// <summary>
 ///     Use this method to override and apply rules to map your entities to BsonDocument
 /// </summary>
 protected virtual void OnModelCreating(BsonMapper mapper)
 {
 }
コード例 #31
0
 /// <summary>
 /// Starts LiteDB database using a Stream disk
 /// </summary>
 public LiteRepository(Stream stream, BsonMapper mapper = null, string password = null)
     : this(new LiteDatabase(stream, mapper, password), true)
 {
 }
コード例 #32
0
 internal EntityBuilder(BsonMapper mapper)
 {
     _mapper = mapper;
     _prop   = mapper.GetPropertyMapper(typeof(T));
 }
コード例 #33
0
 public static void MapLiteDbEntities(LiteDB.BsonMapper mapper)
 {
     mapper.Entity <GameScannerConfig>().Id(a => a.Id, false);
 }
コード例 #34
0
 public QueryVisitor(BsonMapper mapper)
 {
     _mapper     = mapper;
     _type       = typeof(T);
     _parameters = new ParameterDictionary();
 }
コード例 #35
0
 /// <summary>
 /// Use this method to override and apply rules to map your entities to BsonDocument
 /// </summary>
 protected virtual void OnModelCreating(BsonMapper mapper)
 {
 }
コード例 #36
0
 /// <summary>
 /// Starts LiteDB database using a connection string for file system database
 /// </summary>
 public LiteRepository(ConnectionString connectionString, BsonMapper mapper = null)
     : this(new LiteDatabase(connectionString, mapper), true)
 {
 }
コード例 #37
0
 public TorLiteDatabase(IDiskService diskService, BsonMapper mapper = null)
     : base(diskService, mapper)
 {
 }
コード例 #38
0
 internal EntityBuilder(BsonMapper mapper, ITypeNameBinder typeNameBinder)
 {
     _mapper         = mapper;
     _typeNameBinder = typeNameBinder;
     _entity         = mapper.GetEntityMapper(typeof(T));
 }
コード例 #39
0
 /// <summary>
 /// Starts LiteDB database using a connection string for file system database
 /// </summary>
 public LiteRepository(ConnectionString connectionString, BsonMapper mapper = null)
 {
     _db = new LiteDB.LiteDatabase(connectionString, mapper);
 }
コード例 #40
0
        protected override void OnModelCreating(BsonMapper mapper)
        {
            base.OnModelCreating(mapper);

            mapper.Entity<Account>()
                .DbRef(a => a.Members, PetoeterDb.TableMember)
                .DbRef(a => a.Children, PetoeterDb.TableChildren);

            mapper.Entity<Presence>()
                .DbRef(p => p.Child, PetoeterDb.TableChildren)
                .DbRef(p => p.BroughtBy, PetoeterDb.TableMember)
                .DbRef(p => p.TakenBy, PetoeterDb.TableMember);
        }
コード例 #41
0
 /// <summary>
 /// Starts LiteDB database using a Stream disk
 /// </summary>
 public LiteRepository(Stream stream, BsonMapper mapper = null, string password = null)
 {
     _db = new LiteDB.LiteDatabase(stream, mapper, password);
 }
コード例 #42
0
ファイル: LiteRepository.cs プロジェクト: mercan01/LiteDB
 /// <summary>
 /// Starts LiteDB database using a Stream disk
 /// </summary>
 public LiteRepository(Stream stream, BsonMapper mapper = null)
 {
     _db = new LiteDatabase(stream, mapper);
 }