This project has moved. For the latest updates, please go here.

Greater than ObjectId

Aug 26, 2013 at 8:38 PM
Edited Aug 26, 2013 at 8:41 PM
I'm receiving an exception when I attempt to select objects greater than a given ObjectId using the conversion from string to ObjectId suggested in the Documentation section. Does anyone have an idea on how I can select based on ObjectId while getting around this serialization issue?

Exception: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'

Code:
    // GET api/post/list
    [HttpGet]
    public HttpResponseMessage List()
    {
        IQueryable<Post> query;

        var id = new ObjectId("521ba9295539390d08e5f3cb");
        query = repository
            .Where(p => new ObjectId(p.Id) > id)
            .OrderByDescending(p => p.Id);

        return Request.CreateResponse<IEnumerable<Post>>(HttpStatusCode.OK, query);
    }
Aug 27, 2013 at 7:40 PM
In case others run into this issue, I decided to go with a workaround by extending MongoRepository using the lower-level C# MongoDB driver. Following is the code for the extension interface and class:

Interface:
using System;
using System.Collections.Generic;
using MongoRepository;
using App.Models;
using System.Linq.Expressions;

namespace App.DataAccess
{
    interface IEntityRepository : IRepository<Entity>
    {
        IEnumerable<Entity> GetEntitiesGreaterThan(
            Expression<Func<Entity, string>> memberExpression,
            string valueToCompare);
    }
}
Class:
using System;
using System.Collections.Generic;
using MongoRepository;
using App.Models;
using MongoDB.Driver.Builders;
using MongoDB.Driver;
using System.Linq.Expressions;

namespace App.DataAccess
{
    public class EntityRepository : MongoRepository<Entity>, IEntityRepository
    {
        public IEnumerable<Entity> GetEntitiesGreaterThan(
            Expression<Func<Entity, string>> memberExpression,
            string valueToCompare)
        {
            IMongoQuery query = Query<Entity>.GT(memberExpression, valueToCompare);
            return this.Collection.Find(query);
        }
    }
}
Coordinator
Aug 28, 2013 at 7:28 PM
Edited Aug 28, 2013 at 7:31 PM
This exception is thrown because the expression "Where(p => new ObjectId(p.Id) > id)" can't be compiled into a query (think about it: new ObjectId(p.Id) would have to take place in the "application-space", not "Mongo-space"). I should look into this sometime to see if I can come up with a way this expression would compile but it's primarily the underlying MongoDB C# Driver's Linq provider that has trouble with it, not MongoRepository. Your work-around is "hand crafting" a query and not using the dynamic expression using Linq (you could compare this to using Linq2SQL v.s. writing a query using a string). Having said that: as long as it works for you (and mind you, it might be the only way): well done!