在Linq MongodbDriver的“ Where”方法中使用“ Any”方法时出现问题

时间:2019-04-23 11:45:12

标签: c# linq mongodb-.net-driver

我是使用linq的新手,遇到了一些问题。我有一大批A型收藏品和一小批B型收藏品。 我希望A中“ id”确实存在于B中的项目列表。 因此,这就是我认为可行的方法:

List<string> list = collection_A
                .Where(c => collection_B.Any(x => x.MessageId == c.Id))
                .Select(c=>c.Id)
                .ToList();

我在.Net中使用mongoDB linq提供程序,错误是:System.ArgumentException:不支持的过滤器。关系是1-1

实际上,我不知道在这种情况下还是应该使用“加入”。

2 个答案:

答案 0 :(得分:1)

我建议您尝试一下:

var messageIds = new HashSet<string>(collection_B.Select(x => x.MessageId).Distinct());

List<string> list =
    collection_A
        .Where(c => messageIds.Contains(c.Id))
        .Select(c => c.Id)
        .ToList();

答案 1 :(得分:0)

如果我正确理解了您的问题,以下代码将为您指明正确的方向。 我已经使用MongoDAL进行数据访问,这只是c#驱动程序的抽象。

using System;
using System.Linq;
using MongoDAL;

namespace Example
{
    class Person : Entity
    {
        public string Name { get; set; }
    }

    class BanRecord : Entity
    {
        public One<Person> Person { get; set; }
        public string ReasonForBan { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new DB("testdatabase");

            var person1 = new Person { Name = "Person One" };
            var person2 = new Person { Name = "Person Two" };
            var person3 = new Person { Name = "Person Three" };

            person1.Save();
            person2.Save();
            person3.Save();

            var ban1 = new BanRecord
            {
                Person = person1.ToReference(),
                ReasonForBan = "Cause we can!"
            };
            ban1.Save();

            var ban2 = new BanRecord
            {
                Person = person2.ToReference(),
                ReasonForBan = "Cause we can!"
            };
            ban2.Save();

            var bannedPeople = (from b in DB.Collection<BanRecord>()
                                join p in DB.Collection<Person>() on b.Person.ID equals p.ID into banned
                                from p in banned
                                select p).ToArray();

            Console.ReadKey();
        }
    }
}

相关问题