如何在C#中的MongoDb Collection之间应用联接

时间:2018-10-10 07:06:19

标签: c# mongodb asp.net-core-2.0

我以简单的例子来演示我的问题,C#中有2个类

class Table1
    {
        [BsonId]
        public ObjectId _Id { get; set; }

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

class Table2
    {
        [BsonId]
        public ObjectId _Id { get; set; }

        [BsonElement]
        public int Age { get; set; }

        [BsonElement]
        public ObjectId UserId { get; set; }
    }

以下是MongoDB中的数据:
表1:

  

{“ _ id”:“ 5bbd9b904b235724d42d61b1”,“名称”:“ User1”}


表2:

  

{“ _ id”:“ 5bbd9bad4b235724d42d61b2”,“年龄”:25,“ UserId”:“ 5bbd9b904b235724d42d61b1”}


现在在c#控制台应用程序中加入连接

static void ViewRecords()
    {
        MongoContext db = new MongoContext();
        var Table1 = db._database.GetCollection<Table1>("Table1");
        var Table2 = db._database.GetCollection<Table2>("Table2");

        var r = from t1 in Table1.AsQueryable()
                join t2 in Table2.AsQueryable() on t1._Id equals t2.UserId into result
                select new Table1()
                {
                    _Id = t1._Id,
                    Name = t1.Name
                };

        foreach (var a in r)
        {
            Console.WriteLine(a.Name);
        }
    }

现在它引发了异常

  

不支持GroupJoin查询运算符。

我关注的链接:Link

我已经通过nuget软件包管理器安装了mongocsharpdriver 2.7.0和MongoDB.Driver 2.7.0。

在过去的两天里,我一直在努力。.任何支持将不胜感激。

1 个答案:

答案 0 :(得分:0)

当我一次又一次地尝试时,我发现了一些非常有趣的东西。经过几次重大更改,相同功能似乎就可以正常工作。
1.将MongoClient更改为IMongoClient,将MongoDatabase更改为IMongoDatabase

public class MongoContext
    {
        IMongoClient _client;
        public readonly IMongoDatabase _database;

        public MongoContext()
        {
            //Reading credentials from Web.config file
            _client = new MongoClient("mongodb://" + ConfigurationManager.AppSettings["MongoHost"] + ":" + ConfigurationManager.AppSettings["MongoPort"]);
            _database = _client.GetDatabase(ConfigurationManager.AppSettings["MongoDatabaseName"]);
        }
    }

我需要从上下文类中删除MongoServer。

  1. 将ViewRecords方法更改为以下内容:

        static List<Table1> ViewRecords()
    {
        try
        {
            MongoContext db = new MongoContext();
            IMongoCollection<Table1> = db._database.GetCollection<Table1>("Table1");
            IMongoCollection<Table2> = db._database.GetCollection<Table2>("Table2");
    
            var r = from t1 in Table1.AsQueryable()
                    join t2 in Table2.AsQueryable() on t1._Id equals t2.UserId
                    select new Table1()
                    {
                        _Id = t1._Id,
                        Name = t1.Name
                    };
    
            return r.ToList();
        }
        catch (Exception ex) { throw ex; }
    }
    

现在它起作用了。.我从某个博客那里得到了这个提示,如果我再次找到相同的链接,它将分享该链接。