예제 #1
0
        public void should_read_and_set_id()
        {
            MongoQueryProvider provider = MongoTestHelper.create_query_provider();
            Book book = new MongoQuery<Book>(provider).First();

            book.Id.ShouldBe(_book.Id);
        }
예제 #2
0
        public void TestMongoCursor()
        {
            //llenamos datos
            (new InsertModifyDeleteTest()).TestInsert();

            //TODO: Falla el OutPut cuando ya hemos pedido el cursor ver como hacerlo
            //A MongoCursor object cannot be modified once it has been frozen
            ConfigManager.Out = null;


            var Countries = CountryCollection.Instance;

            Countries.Find();
            Assert.AreEqual(Countries.Count, 3);

            Countries.Find().Skip(2);
            Assert.AreEqual(Countries.Count, 1);

            Countries.Find().Limit(1);
            Assert.AreEqual(Countries.Count, 1);

            Countries.Find(MongoQuery <Country> .Eq(c => c.Code, "ES")).Project(Countries.Project.Include(C => C.Code));
            Assert.AreEqual(Countries.Count, 1);
            //var c2 = Countries.First();
            //TODO Projection no esta funcionando, devuelve Name tambien Assert.AreEqual(c2.Name, null);
        }
예제 #3
0
        public void TestCollectionExtensions()
        {
            Helper.DropAllCollections();

            //Insert de Paises
            var c = new Country {
                Code = "ES", Name = "España"
            };

            c.Save();
            c = new Country {
                Code = "UK", Name = "Reino Unido"
            };
            c.Save();
            c = new Country {
                Code = "US", Name = "Estados Unidos"
            };
            c.Save();

            var countries = new List <Country>();

            countries.MongoFind();
            Assert.AreEqual(countries.Count, 3);

            countries.MongoFind(MongoQuery <Country> .Eq(co => co.Code, "ES"));
            Assert.AreEqual(countries.Count, 1);
            Assert.AreEqual(countries[0].Code, "ES");

            countries.MongoFind(
                Builders <Country> .Filter.Or(MongoQuery <Country> .Eq(co => co.Code, "ES"), MongoQuery <Country> .Eq(co => co.Code, "UK")));
            Assert.AreEqual(countries.Count, 2);
        }
예제 #4
0
        public void should_read_and_set_id()
        {
            MongoQueryProvider provider = MongoTestHelper.create_query_provider();
            Customer customer = new MongoQuery<Customer>(provider).First();

            customer.Id.ShouldBe(_customer.Id);
        }
예제 #5
0
        /// <summary>
        /// Gets the query.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="selector">The selector.</param>
        /// <returns></returns>
        private static Document GetQuery <T>(IMongoCollection <T> collection, Expression <Func <T, bool> > selector) where T : class
        {
            var query = new MongoQuery <T>(new MongoQueryProvider(collection.Database, collection.Name))
                        .Where(selector);
            var queryObject = ((IMongoQueryable)query).GetQueryObject();

            return(queryObject.Query);
        }
예제 #6
0
        public ActionResult Details(Guid id)
        {
            var model = new ProductSummaryModel();

            var query = new MongoQuery<ProductSummary>(_mongoQueryProvider);

            var summary = query.FirstOrDefault(productSummary => productSummary.ProductId == id);

            model.Name = summary.Name;
            model.ProductId = summary.ProductId;

            return View(model);
        }
        public void delete_customer()
        {
            var customer = new Customer
                               {
                                   Name = "Han Solo"
                               };
            _mongo.GetCollection<Customer>().Insert(customer);

            Customer customerToDelete = new MongoQuery<Customer>(_provider).First();

            _mongo.GetCollection<Customer>().Delete(customerToDelete);

            _mongo.GetCollection<Customer>().Count().ShouldBe(0);
        }
        private object GetFromLocalCache <T>(string objectName, string fieldNames, params object[] values)
        {
            if (values.Any(value => value == null))
            {
                return(null);
            }

            string valueKey = values.Aggregate(String.Empty, (current, value) => current + (value.ToString() + "|"));

            string key = (string.Format("{0}|{1}|{2}", objectName, fieldNames, valueKey));

            if (!LocalCache.ContainsKey(key))
            {
                var queryList = new List <FilterDefinition <T> >();
                int index     = 0;
                var fields    = fieldNames.Split(',');
                foreach (var value in values)
                {
                    FilterDefinition <T> query;
                    if (value is long)
                    {
                        query = MongoQuery <T> .Eq(objectName, fields[index], (long)value);
                    }
                    else if (value is int)
                    {
                        query = MongoQuery <T> .Eq(objectName, fields[index], (int)value);
                    }
                    else
                    {
                        query = MongoQuery <T> .Eq(objectName, fields[index], value.ToString());
                    }
                    queryList.Add(query);
                    index++;
                }

                var cursor = MongoMapperCollection <T> .Instance.Find(Builders <T> .Filter.And(queryList)).ToListAsync().Result;

                object data = null;
                if (cursor.Any())
                {
                    data = cursor.First();
                }

                if (!LocalCache.ContainsKey(key))
                {
                    LocalCache.Add(key, data);
                }
            }
            return(LocalCache[key]);
        }
예제 #9
0
        public void TestPopCustomSortCustomQuery()
        {
            Helper.DropAllCollections();

            var c = new Country {
                Code = "A", Name = "1"
            };

            c.Save();
            c = new Country {
                Code = "B", Name = "1"
            };
            c.Save();
            c = new Country {
                Code = "C", Name = "C"
            };
            c.Save();
            c = new Country {
                Code = "D", Name = "1"
            };
            c.Save();

            var countries = new CountryCollection();

            countries.Find();

            Assert.AreEqual(4, countries.Count);

            c = countries.Pop(MongoQuery <Country> .Eq(C => C.Name, "1"), countries.Sort.Descending(C => C.Code));

            Assert.AreEqual(c.Code, "D");

            Assert.AreEqual(3, countries.Count);

            c = countries.Pop(MongoQuery <Country> .Eq(C => C.Name, "1"), countries.Sort.Descending(C => C.Code));

            Assert.AreEqual(c.Code, "B");

            Assert.AreEqual(2, countries.Count);

            c = countries.Pop(MongoQuery <Country> .Eq(C => C.Name, "1"), countries.Sort.Descending(C => C.Code));

            Assert.AreEqual(c.Code, "A");

            Assert.AreEqual(1, countries.Count);

            c = countries.Pop(MongoQuery <Country> .Eq(C => C.Name, "1"), countries.Sort.Descending(C => C.Code));

            Assert.IsNull(c);
        }
예제 #10
0
        public void Test()
        {
            Helper.DropAllCollections();

            var country = new Country {
                Code = "NL", Name = "Holanda"
            };

            country.Save();
            country = new Country {
                Code = "UK", Name = "Reino Unido"
            };
            country.Save();
            country = new Country {
                Code = "ES", Name = "España"
            };
            country.Save();

            var col = new CountryCollection {
                FromPrimary = false
            };

            col.Find();

            foreach (Country c in col)
            {
                Console.WriteLine(c.Name);
            }

            col.Find().Limit(1);

            //Console.WriteLine(col.Cursor.Explain().ToJson());

            Assert.AreEqual(1, col.Count);
            Assert.AreEqual(3, col.Total);

            col = new CountryCollection {
                FromPrimary = true
            };
            col.Find().Limit(3).Sort(col.Sort.Ascending(C => C.Name));

            Assert.AreEqual(3, col.Count);
            Assert.AreEqual("ES", col.First().Code);

            col.Find(MongoQuery <Country> .Eq(C => C.Code, "NL"));

            Assert.AreEqual("NL", col.First().Code);
            //TODO: No esta implementado el last Assert.AreEqual("NL", col.Last().Code);
        }
예제 #11
0
파일: LinqTests.cs 프로젝트: perikete/NoRM
        public void CanQueryAndReturnSubClassedObjects_EvenWhenAddedBySubClass()
        {
            using (var session = new Session())
            {
                session.Drop<SuperClassObject>();

                session.Add(new SubClassedObject());

                var query = new MongoQuery<SuperClassObject>(session.Provider);

                var dtos = query.ToList();

                Assert.Equal(1, dtos.Count);
            }
        }
예제 #12
0
        public void delete_book()
        {
            var book = new Book
                           {
                               Title = "Ender's Game",
                               Author = "Orson Scott Card",
                           };
            _mongo.GetCollection<Book>().Insert(book);

            Book bookToDelete = new MongoQuery<Book>(_provider).First();

            _mongo.GetCollection<Book>().Delete(bookToDelete);

            _mongo.GetCollection<Book>().Count().ShouldBe(0);
        }
        public void update_customer()
        {
            var customer = new Customer
                               {
                                   Name = "Han Solo"
                               };
            _mongo.GetCollection<Customer>().Insert(customer);

            Customer customerToUpdate = new MongoQuery<Customer>(_provider).First();
            customerToUpdate.Name = "Luke Skywalker";

            _mongo.GetCollection<Customer>().Save(customerToUpdate);

            _mongo.GetCollection<Customer>().Count().ShouldBe(1);
            new MongoQuery<Customer>(_provider).First().Name.ShouldBe("Luke Skywalker");
        }
예제 #14
0
파일: LinqTests.cs 프로젝트: perikete/NoRM
        public void CanQueryAndReturnSubClassedObjects_EvenWhenQueriedByInterface()
        {
            using (var session = new Session())
            {
                session.Drop<IDiscriminated>();

                var obj = new InterfaceDiscriminatedClass();
                session.Add(obj);

                var query = new MongoQuery<IDiscriminated>(session.Provider);

                var dtos = query.ToList();

                Assert.Equal(1, dtos.Count);
                Assert.Equal(obj.Id, dtos.Single().Id);
            }
        }
예제 #15
0
파일: LinqTests.cs 프로젝트: gleborgne/NoRM
        public void CanQueryAndReturnSubClassedObjects()
        {
            using (var session = new Session())
            {
                session.Drop<SuperClassObject>();

                session.Add<SuperClassObject>(new SubClassedObject { Title = "Find This", ABool = true });
                session.Add<SuperClassObject>(new SubClassedObject { Title = "Don't Find This", ABool = false });

                var query = new MongoQuery<SuperClassObject>(session.Provider);

                var dtos = query.Where(dto => dto.Title == "Find This").ToList();

                Assert.Equal(1, dtos.Count);
                Assert.Equal("Find This", dtos[0].Title);
            }
        }
예제 #16
0
        public void TestPerfMongoFindNormalVsExtensionMethods()
        {
            Helper.DropAllCollections();

            //Insert de Paises
            var c = new Country {
                Code = "ES", Name = "España"
            };

            c.Save();
            c = new Country {
                Code = "UK", Name = "Reino Unido"
            };
            c.Save();
            c = new Country {
                Code = "US", Name = "Estados Unidos"
            };
            c.Save();

            Stopwatch timer = Stopwatch.StartNew();

            for (int i = 0; i < 1000000; i++)
            {
                var countries = new List <Country>();
                countries.MongoFind(
                    Builders <Country> .Filter.Or(MongoQuery <Country> .Eq(co => co.Code, "ES"), MongoQuery <Country> .Eq(co => co.Code, "UK")));
            }
            timer.Stop();
            Console.WriteLine(string.Format("Elapsed para ExtensionMethod: {0}", timer.Elapsed));
            //Elapsed para ExtensionMethod: 00:04:29.8042031

            timer = Stopwatch.StartNew();

            for (int i = 0; i < 1000000; i++)
            {
                CountryCollection mongoCol = new CountryCollection();
                mongoCol.Find(
                    mongoCol.Filter.Or(MongoQuery <Country> .Eq(co => co.Code, "ES"), MongoQuery <Country> .Eq(co => co.Code, "UK")));
                mongoCol.ToList();
            }

            timer.Stop();
            Console.WriteLine(string.Format("Elapsed para StaticMethod: {0}", timer.Elapsed));
            //Elapsed para StaticMethod: 00:04:10.1821050
        }
        public void TestServerDelete()
        {
            Helper.DropAllCollections();

            for (int i = 0; i < 100; i++)
            {
                var c = new Country {
                    Code = i.ToString(), Name = String.Format("Nombre {0}", i)
                };
                c.Save();

                Assert.AreEqual(i + 1, CountryCollection.Instance.Find().CountAsync().Result);
            }

            MongoMapper <Country> .ServerDelete(MongoQuery <Country> .Eq(c => c.Code, "0"));

            Assert.AreEqual(99, CountryCollection.Instance.Find().CountAsync().Result);
        }
예제 #18
0
        public virtual async Task <IEnumerable <T> > Query <T>(MongoQuery query, ISessionCache sessionCache, ITrackingProvider tracking)
            where T : class
        {
            var pipe = new Middleware <QueryContext, IEnumerable <LoadContext> >();

            pipe.Use(new TrackingAction(tracking));
            pipe.Use(new UpdateCacheAction(sessionCache));
            pipe.Use(new OverrideUsingCacheAction <LoadContext>(sessionCache));
            pipe.Use(new MongoQueryFromDatabaseAction(_couchDb, _idManager, _idAccessor));

            //setup the load context
            var type = typeof(T);

            var ctx = new QueryContext()
            {
                Query = query,
                Type  = type
            };

            var results = await pipe.Execute(ctx);

            return(results.Select(x => x.Entity).Where(x => x != null).Cast <T>());
        }
예제 #19
0
        public void Filter()
        {
            var Fields  = new string[] { "Description" };
            var OrderBy = new string[] { "lmd", "CurrencyCode" };

            string Name  = "%";
            int    Skip  = 25;
            int    Limit = 25;

            var col = MongoMapperCollection <CurrencyType> .Instance;

            Fields = MongoMapperHelper.ConvertFieldName("CurrencyType", Fields.ToList()).ToArray();

            OrderBy = MongoMapperHelper.ConvertFieldName("CurrencyType", OrderBy.ToList()).ToArray();
            var sortList = new List <SortDefinition <CurrencyType> >();

            if (!OrderBy.Any() || string.IsNullOrEmpty(OrderBy.First()))
            {
                sortList.Add(col.Sort.Ascending("$natural"));
            }

            sortList.AddRange(OrderBy.Where(S => !string.IsNullOrEmpty(S)).Select(Field => col.Sort.Ascending(Field)));

            var order = col.Sort.Combine(sortList);

            col.AddIncludeFields(Fields);

            col.Find(col.Filter.And(MongoQuery <CurrencyType> .Eq(D => D.Name, Name))).Limit(Limit).Skip(Skip).Sort(order);


            Console.WriteLine(col.Count);
            foreach (var currencyType in col)
            {
                Console.WriteLine(currencyType.CurrencyCode);
                Console.WriteLine(currencyType.Description);
            }
        }
예제 #20
0
        public void TestFindAnddOr()
        {
            var Countries = CountryCollection.Instance;
            var Persons   = MongoMapperCollection <Person> .Instance;

            Countries.Find(MongoQuery <Country> .Eq(c => c.Code, BsonNull.Value));

            //Llenamos datos
            (new InsertModifyDeleteTest()).TestInsert();

            ConfigManager.Out = Console.Out;



            Countries.Find(
                Countries.Filter.Or(MongoQuery <Country> .Eq(c => c.Code, "ES"), MongoQuery <Country> .Eq(c => c.Code, "UK")));
            Assert.AreEqual(Countries.Count, 2);

            Persons.Find(
                Persons.Filter.And(MongoQuery <Person> .Eq(p => p.Age, 25), MongoQuery <Person> .Eq(p => p.Country, "ES")));
            Assert.AreEqual(Persons.Count, 2);

            Persons = new MongoMapperCollection <Person>();
            Persons.Find(
                Persons.Filter.And(MongoQuery <Person> .Eq(p => p.Age, 35), MongoQuery <Person> .Eq(p => p.Country, "%")));
            Assert.AreEqual(1, Persons.Count);

            Persons = new MongoMapperCollection <Person>();

            Persons.Find(MongoQuery <Person> .Eq(p => p.Name, "%perez%"));
            Assert.AreEqual(2, Persons.Count);


            Persons.Find(MongoQuery <Person> .Eq(p => p.Name, "j%"));
            Assert.AreEqual(2, Persons.Count);

            Persons.Find(MongoQuery <Person> .Eq(p => p.Name, "%Z"));
            Assert.AreEqual(3, Persons.Count);


            Persons.Find(MongoQuery <Person> .Eq(p => p.Married, false));
            Assert.AreEqual(3, Persons.Count);

            Persons.Find(Persons.Filter.And(MongoQuery <Person> .Eq(p => p.Age, 25), MongoQuery <Person> .Eq(p => p.Country, "ES")));
            Assert.AreEqual(2, Persons.Count);


            foreach (Person p in Persons)
            {
                Assert.AreEqual(p.Age, 25);
                Assert.AreEqual(p.Country, "ES");
            }

            Persons.Find(Persons.Filter.And(MongoQuery <Person> .Eq(p => p.Age, 25), MongoQuery <Person> .Eq(p => p.Country, "US")));
            Assert.AreEqual(0, Persons.Count);

            Persons.Find(MongoQuery <Person> .Gt(p => p.Age, 25));
            Assert.AreEqual(2, Persons.Count);


            Persons.Find(MongoQuery <Person> .Gte(p => p.Age, 25));
            Assert.AreEqual(4, Persons.Count);

            Persons.Find(MongoQuery <Person> .Lt(p => p.Age, 25));
            Assert.AreEqual(1, Persons.Count);

            Persons.Find(MongoQuery <Person> .Lte(p => p.Age, 25));
            Assert.AreEqual(3, Persons.Count);
        }
예제 #21
0
        public void update_book()
        {
            var book = new Book
                           {
                               Title = "Ender's Game",
                               Author = "Orson Scott Card",
                           };
            _mongo.GetCollection<Book>().Insert(book);

            Book bookToUpdate = new MongoQuery<Book>(_provider).First();
            bookToUpdate.Title = "Hidden Empire";

            _mongo.GetCollection<Book>().Save(bookToUpdate);

            _mongo.GetCollection<Book>().Count().ShouldBe(1);
            new MongoQuery<Book>(_provider).First().Title.ShouldBe("Hidden Empire");
        }
예제 #22
0
        private static void QueryConditionalOperatorsUsingLinq(MongoQuery<Order> orders)
        {
            Console.WriteLine("\n\n======= Query with Conditional Operators (Using Linq) =======");
            var ordersWithAmountGreaterThan50 = from order in orders
                                                where order.OrderAmount > 50
                                                select order;
            var ordersWithAmountGreaterThanOEqualTo50 = from order in orders
                                                        where order.OrderAmount >= 50
                                                        select order;
            var ordersWithAmountLessThan100 = from order in orders
                                              where order.OrderAmount < 100
                                              select order;
            var ordersWithAmountLessThanOEqualTo100 = from order in orders
                                                      where order.OrderAmount <= 100
                                                      select order;
            var ordersWithAmountBetween50And200 = from order in orders
                                                  where order.OrderAmount > 50 && order.OrderAmount < 200
                                                  select order;
            var ordersWithAmountNotEqualTo100= from order in orders
                                                  where order.OrderAmount != 100
                                                  select order;
            var ordersWithAmountInList = from order in orders
                                         where new List<string> {"Elmer Fudd", "Daffy Duck"}.Contains( order.CustomerName )
                                         select order;

            Console.WriteLine("\nOrders with amount greater than 50:");
            foreach ( var order in ordersWithAmountGreaterThan50 )
                Console.WriteLine(order.ToString());

            Console.WriteLine("\nOrders with amount greater than or equal to 50:");
            foreach ( var order in ordersWithAmountGreaterThanOEqualTo50 )
                Console.WriteLine(order.ToString());

            Console.WriteLine("\nOrders with amount less than 100:");
            foreach ( var order in ordersWithAmountLessThan100 )
                Console.WriteLine(order.ToString());

            Console.WriteLine("\nOrders with amount less than or equal to 100:");
            foreach ( var order in ordersWithAmountLessThanOEqualTo100 )
                Console.WriteLine(order.ToString());

            Console.WriteLine("\nOrders with amount between 50 and 200:");
            foreach ( var order in ordersWithAmountBetween50And200 )
                Console.WriteLine(order.ToString());

            Console.WriteLine("\nOrders with amount not equal to 100:");
            foreach ( var order in ordersWithAmountNotEqualTo100 )
                Console.WriteLine(order.ToString());

            Console.WriteLine("\nOrders with amount in list:");
            foreach ( var order in ordersWithAmountInList )
                Console.WriteLine(order.ToString());
        }
예제 #23
0
        /// <summary>
        /// Demo querying the collection with Linq.
        /// </summary>
        /// <param name="orders">The orders.</param>
        private static void QueryUsingLinq(MongoQuery<Order> orders)
        {
            Console.WriteLine("\n\n======= Query Using Linq =======");

            // Query the orders collection.
            IQueryable<Order> results =
                    from order in orders
                    where order.CustomerName == "Elmer Fudd"
                    select order;
            var result = results.FirstOrDefault();

            Console.WriteLine(string.Format("Found: {0}", result));
        }
예제 #24
0
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        private static void Main( string[] args )
        {
            var mongo = new Mongo( "myorders", "localhost", "27017", string.Empty );
            // For Linq to work, collection name must match Class name.
            MongoCollection< Order > collection = mongo.GetCollection< Order >( "Order" );

            var provider = new MongoQueryProvider(mongo);
            var orderQueryable = new MongoQuery< Order >( provider );

            DeleteAllDocumentsFromCollection( collection );
            CreateAndInsertSingleDocumentIntoCollection( collection );
            CreateAndInsertMultipleDocumentIntoCollection( collection );
            UpdateDocument( collection );
            UpdateUsingAtomicIncrement(collection);
            QueryFromCollection( collection );
            QueryUsingLinq( orderQueryable );
            QueryAllDocuments(orderQueryable);

            QueryConditionalOperators( collection );
            QueryConditionalOperatorsUsingLinq(orderQueryable);

            Console.WriteLine( "\n Press Enter to Exit." );
            Console.ReadLine();
        }
예제 #25
0
        public void Test()
        {
            Helper.DropAllCollections();

            ConfigManager.Out = Console.Out;

            var c = new Country {
                Code = "es", Name = "España"
            };

            try
            {
                c.Save();
                Assert.Fail();
            }
            catch (ValidatePropertyException ex)
            {
                Assert.AreEqual(ex.GetBaseException().GetType(), typeof(ValidatePropertyException));
                c.Code = "ES";
                c.Save();
            }

            c = new Country {
                Code = "UK", Name = "Reino Unido"
            };
            c.Save();

            c = new Country {
                Code = "UK", Name = "Reino Unido"
            };
            try
            {
                c.Save();
                Assert.Fail();
            }
            catch (DuplicateKeyException ex)
            {
                Assert.AreEqual(ex.GetBaseException().GetType(), typeof(DuplicateKeyException));
            }

            using (var t = new MongoMapperTransaction())
            {
                var c2 = new Country {
                    Code = "US", Name = "Francia"
                };
                c2.OnBeforeInsert += (s, e) => { ((Country)s).Name = "Estados Unidos"; };
                c2.Save();

                t.Commit();
            }

            var c3 = new Country();

            c3.FillByKey("US");
            Assert.AreEqual(c3.Name, "Estados Unidos");

            if (!c3.IsLastVersion())
            {
                c3.FillFromLastVersion();
            }

            var countries = new CountryCollection();

            countries.Find();
            Assert.AreEqual(countries.Count, 3);

            countries.Find().Limit(2).Sort(countries.Sort.Ascending(C => C.Name));
            Assert.AreEqual(countries.Count, 2);
            Assert.AreEqual(countries.Total, 3);

            countries.Find(
                countries.Filter.Or(MongoQuery <Country> .Eq(co => co.Code, "ES"), MongoQuery <Country> .Eq(co => co.Code, "UK")));
            Assert.AreEqual(countries.Count, 2);

            var p = new Person
            {
                Name        = "Pepito Perez",
                Age         = 35,
                BirthDate   = DateTime.Now.AddDays(57).AddYears(-35),
                Married     = true,
                Country     = "XXXXX",
                BankBalance = decimal.Parse("3500,00")
            };

            p.Childs.Add(
                new Child {
                ID = 1, Age = 10, BirthDate = DateTime.Now.AddDays(57).AddYears(-10), Name = "Juan Perez"
            });

            try
            {
                p.Save();
                Assert.Fail();
            }
            catch (ValidateUpRelationException ex)
            {
                Assert.AreEqual(ex.GetBaseException().GetType(), typeof(ValidateUpRelationException));
                p.Country = "ES";
                p.Save();
            }

            p.ServerUpdate(
                p.Update.Push(
                    MongoMapperHelper.ConvertFieldName("Person", "Childs"),
                    new Child {
                ID = 2, Age = 2, BirthDate = DateTime.Now.AddDays(57).AddYears(-7), Name = "Ana Perez"
            }));

            var persons = new List <Person>();

            persons.MongoFind();

            persons.MongoFind("Childs.Age", 2);
            Assert.AreEqual(1, persons.Count);
        }
예제 #26
0
        public override object Execute(Expression expression)
        {
            //preprocess
            expression = PartialEvaluator.Eval(expression);
            //expression = EnumParameterEvaluator.Eval(expression);
            var linqQuery = LinqVisitor.Eval(expression);

            //get the type constraint
            var types      = _sessionContext.TypeManager.Implementation(typeof(T)).Select(x => $"{x.FullName}, {x.GetTypeInfo().Assembly.GetName().Name}");
            var typesQuery = new QueryObject {
                { "\\$type", new QueryObject {
                      { "$in", types }
                  } }
            };

            var clauses = new List <IDictionary <string, object> >();

            clauses.Add(typesQuery);

            _sessionContext.QueryPart = QueryPart.Where;
            //get all the other where clauses
            foreach (var whereClause in linqQuery.WhereClauses)
            {
                var partial = MongoQueryTransformVisitor.Eval(whereClause, _sessionContext);
                clauses.Add(partial);
            }

            //either take the single where clause or "and" them all together
            IDictionary <string, object> query;

            if (clauses.Count == 1 && !linqQuery.Ordering.Any())
            {
                query = clauses.First();
            }
            else
            {
                query = new QueryObject()
                {
                    { "$and", clauses }
                };
            }

            //sorting / orderby
            _sessionContext.QueryPart = QueryPart.OrderBy;
            var handler = new OrderByHandler(_sessionContext);
            var orders  = new List <IDictionary <string, Order> >();

            foreach (var orderBy in linqQuery.Ordering)
            {
                IDictionary <string, Order> order = new Dictionary <string, Order>();
                var name = handler.GetMemberName((MemberExpression)((LambdaExpression)((UnaryExpression)orderBy.Expression).Operand).Body);
                var or   = orderBy.Direction == OrderByDirection.Asc ? Order.Asc : Order.Desc;
                order.Add(name, or);
                orders.Add(order);

                //add the name to the selector.
                var sortSelector = new QueryObject {
                    { name, new QueryObject {
                          { "$gt", null }
                      } }
                };
                clauses.Add(sortSelector);
            }

            object index = null;

            if (_index != null && _index.Any())
            {
                index = _index.Count() == 1 ? (object)_index.First() : (object)_index;
            }

            var mongoQuery = new MongoQuery()
            {
                Index    = index,
                Selector = query,
                Skip     = linqQuery.Paging.Skip,
                Limit    = linqQuery.Paging.Take,
                Sort     = orders.Count == 0 ? null : orders
            };

            var collection = _session.Query <T>(mongoQuery);

            if (linqQuery.ParentQuery == null)
            {
                return(linqQuery.PostProcess.Execute(collection));
            }

            //we have only run some of the query, this will setup the rest
            linqQuery.ParentQuery.RewriteSource(collection);
            var exp = linqQuery.ParentQuery.Expression;

            //run the expression!
            var result = Expression.Lambda(exp).Compile().DynamicInvoke();

            return(result);
        }
예제 #27
0
 /// <summary>
 /// Demo of Querying the collection.
 /// </summary>
 /// <param name="collection">The collection.</param>
 private static void QueryAllDocuments(MongoQuery<Order> orders)
 {
     Console.WriteLine( "\n\n======= Query All Documents =======" );
     foreach ( Order order in orders )
         Console.WriteLine( string.Format( "Found: {0}", order ) );
 }