首页 > 解决方案 > 具有泛型类型的 GroupBy 之后的 MongoDb C# 驱动程序投影

问题描述

我在使用 mongodb c# 驱动程序(v 2.11.1)时发现了一个问题,我需要执行 GroupBy 并在从每个组中选择第一个 id 之后。

在处理具体的 IMongoQueryable 时,它​​工作正常。但是,当我用一些通用帮助程序类包装它时,我得到了不受支持的方法消息的异常。

这是显示错误的 dotnet 核心控制台应用程序的代码。看起来在 groupby 之后的 Select 并没有针对具体的泛型实现。

using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var sut = new Test<Quote>();

            var workingTest1 = sut.QueryableCollection.GroupBy(x => x._id).Select(x => x.First()._id).ToString();
            var workingTest2 = sut.TestCallWithCasting();

            var notWorkingTest = sut.TestCallWithoutCasting();
        }
    }

    public class Test<TEntity> where TEntity : IMongoDbEntity
    {
        private IMongoCollection<TEntity> _collection;
        public IMongoQueryable<TEntity> QueryableCollection => _collection.AsQueryable();
        public Test()
        {
            var client = new MongoClient();
            var database = client.GetDatabase("Quote");
            _collection = database.GetCollection<TEntity>("quotes");
        }
        public string TestCallWithCasting()
        {
            var t1 = ((IMongoQueryable<Quote>)QueryableCollection).GroupBy(x => x._id).Select(x => x.First()._id).ToString();
            return t1;
        }
        public string TestCallWithoutCasting()
        {
            try
            {
                return QueryableCollection.GroupBy(x => x._id).Select(x => x.First()._id).ToString();

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }

    public class Quote : IMongoDbEntity
    {
        public string _id { get; set; }
    }
    public interface IMongoDbEntity : IEntity
    {
        string _id { get; set; }
    }
    public interface IEntity
    {
    }
}

标签: c#mongodb

解决方案


如果只知道是一个接口,则看起来IMongoQueryable<T>行为不同。如果您在之前添加in不会抛出异常。TTestCallWithoutCastingclassIMongoDbEntityTEntity : IMongoDbEntity

所以最后是这样的:

public class Test<TEntity> where TEntity : class, IMongoDbEntity

推荐阅读