c# - 具有泛型类型的 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
{
}
}
解决方案
如果只知道是一个接口,则看起来IMongoQueryable<T>
行为不同。如果您在之前添加in不会抛出异常。T
TestCallWithoutCasting
class
IMongoDbEntity
TEntity : IMongoDbEntity
所以最后是这样的:
public class Test<TEntity> where TEntity : class, IMongoDbEntity
推荐阅读
- python - 如何从python中的通用列表中获取该输出
- java - JPA - 映射复合主键 OneToMany
- flutter - ListView Horizontal PageScrollPhysics 未对齐项目中心
- search - 扫描庞大的语料并找到相关信息以供用户搜索的方法是什么
- r - geom_density:不同x轴值的着色密度表面
- flutter - 如何在 Flutter 中使用类名作为变量
- reactjs - Next.js amp-story 客户端渲染
- c++ - 访问头文件中定义的私有变量时出现未声明的范围错误
- r - 在 R 中的两个命名列表之间应用函数的最佳方法是什么?
- vulkan - vkGetPhysicalDeviceMemoryProperties 返回无效的 memoryTypeCount