简体   繁体   English

通过 MongoDBRef 在 C# 中查询 MongoDB

[英]Query MongoDB in C# by MongoDBRef

I'm trying to get all Photos of an User, querying by it's UserId reference.我正在尝试获取用户的所有照片,通过它的 UserId 引用进行查询。 (I know about embedded documents in Mongo, but this is how I'd like to use it). (我知道 Mongo 中的嵌入式文档,但这就是我想使用它的方式)。

Here is the error I get: "System.InvalidOperationException: '{UserId.$id}.ToString() is not supported'"这是我得到的错误: "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;
}

A "normal" query like this works without problems:像这样的“正常”查询没有问题:

public List<User> GetAllUsers() => _users.find(user => true).ToList();

Here are my models:这是我的模型:

    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; }
    }

The problem here is that .Find() method takes Expression<T,bool> as parameter and then when you hit .ToList() MongoDB driver tries to convert such expression into MongoDB query / aggregation language.这里的问题是.Find()方法将Expression<T,bool>作为参数,然后当您点击.ToList() MongoDB 驱动程序尝试将此类表达式转换为 MongoDB 查询/聚合语言。 MongoDB .NET driver doesn't understand {UserId.$id}.ToString() and therefore you're getting an exception. MongoDB .NET 驱动程序不理解{UserId.$id}.ToString() ,因此您会遇到异常。

To fix it you should try the other way around - convert your variable in-memory to a type that's stored in the database, try:要修复它,您应该尝试相反的方法 - 将内存中的变量转换为存储在数据库中的类型,请尝试:

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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM