无法确定MongoDB中简单equals运算符的表达式的序列化信息

时间:2015-04-09 10:36:21

标签: c# linq mongodb mongodb-query

我目前遇到的问题是我无法使用Expression<Func<TDocument, bool>>谓词进行简单的i => i.UserName == username查询。

我有以下模型类:

public class ApplicationUser : IApplicationUser
{

    public ApplicationUser()
    {
        // Generate a new Id for the user. This will be overwritten upon retrieval.
        this.Id = ObjectId.GenerateNewId().ToString();
    }

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

    [BsonElement]
    public string UserName { get; set; }

    [BsonElement]
    public string FirstName { get; set; }

    [BsonElement]
    public string LastName { get; set; }

    [BsonElement]
    public DateTime Created { get; set; }
}

在我的代码中,我这样查询mongo集合:

public class UserRepository : IUserRepository
{

    private MongoCollection<IApplicationUser> _collection;

    /// <summary>
    /// Creates a new instance of the UserRepository object.
    /// </summary>
    public UserRepository()
    {

        // Load the configuration to read the connection string
        string connectionString = ConfigurationManager.ConnectionStrings["MongoServer"].ConnectionString;
        MongoUrl mongoUrl = new MongoUrl(connectionString);

        // Specify the mongo client, db and collection objects.
        _mongoClient = new MongoClient(mongoUrl);
        _mongoDb = _mongoClient.GetServer().GetDatabase(mongoUrl.DatabaseName);
        _collection = _mongoDb.GetCollection<IApplicationUser>(COLLECTION_NAME);
    }

    /// <summary>
    /// Returns an enumerable of the objects in the collection that match     the query.
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public IEnumerable<IApplicationUser> Find(Expression<Func<IApplicationUser, bool>> query)
    {
        // Return the enumerable of the collection
        return _collection.AsQueryable().Where(query);
    }

}

我正在调用find方法,例如:

IApplicationUser fromDB = _repository.Find(i => i.FirstName == "Test").FirstOrDefault();

但是这会返回以下消息: Unable to determine the serialization information for the expression

但是我很难过为什么。有没有人想过为什么会这样?看起来很简单。

我试图实现一个未与Mongo耦合的存储库,因此我不希望Find方法采用IMongoQuery对象类型。

干杯, 贾斯汀

0 个答案:

没有答案