我正在尝试获取用户的所有照片,并通过其UserId参考进行查询。 (我知道Mongo中的嵌入式文档,但这是我想使用的方式)。
这是我得到的错误:"System.InvalidOperationException: '{UserId.$id}.ToString() is not supported'"
public ICollection<Photo> GetAllUserPhotos(string userId)
{
var photos = _photos.Find(photo => photo.UserId.Id.ToString() == userId);
var photoListTest = photos.ToList() // here I get the error
return photoListTest;
}
这样的“正常”查询可以正常工作:
public List<User> GetAllUsers() => _users.find(user => true).ToList();
这是我的模特:
public class User
{
[BsonRepresentation(BsonType.ObjectId)]
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
}
public class Photo
{
[BsonRepresentation(BsonType.ObjectId)]
[BsonId]
public string Id { get; set; }
public MongoDBRef UserId { get; set; }
}
这里的问题是.Find()
方法将Expression<T,bool>
作为参数,然后在您单击.ToList()
时,MongoDB驱动程序尝试将此类表达式转换为MongoDB查询/聚合语言。 MongoDB .NET驱动程序不理解{UserId.$id}.ToString()
,因此会出现异常。
要修复它,您应该尝试另一种方法-将内存中的变量转换为存储在数据库中的类型,请尝试:
var userIdConverted = ObjectId.Parse(userId); // or use string if it's string in your database
var dbRef = new MongoDBRef("colName", userIdConverted);
var photos = _photos.Find(photo => photo.UserId.Id.ToString() == dbRef );