gpt4 book ai didi

C# Mongo - Linq 按枚举过滤 -> 转换异常

转载 作者:行者123 更新时间:2023-12-03 15:59:33 27 4
gpt4 key购买 nike

我尝试像这样过滤我的 mongo 集合:

    public IMongoCollection<T> GetCollection<T>()
where T : class
{
return _database.GetCollection<T>(typeof(T).Name);
}


public IMongoQueryable<TModel> Get<TModel>() where TModel : class
{
return GetCollection<TModel>().AsQueryable();
}


public async Task<TModel> FindOneAsync<TModel>(Expression<Func<TModel, bool>> predicate) where TModel : class
{
var foundEntity = await Get<TModel>().FirstOrDefaultAsync(predicate);
if (foundEntity == null)
{
throw new NotFoundException();
}

return foundEntity;
}

然后像这样调用它:

return await Db.FindOneAsync<Node>(node => node.Type == NodeType.Start);

但 mongo 驱动程序内的枚举转换器似乎有错误。我收到以下错误:

Application startup exception: System.AggregateException: One or more errors occurred. (Convert({document}.Type, Int32) is not supported.) ---> System.InvalidOperationException: Convert({document}.Type, Int32) is not supported.

不知道我做错了什么。如果我首先将可查询的内容转换为列表,那么一切都工作正常!但随后过滤操作正在 ram 上运行。

最佳答案

似乎无法重现该错误。以下是使用最新驱动程序的情况。您的驱动程序和服务器版本是什么?

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace StackOverflow
{
public class Program
{
public enum NodeType
{
Start = 1,
End = 2
}

public class Node
{
public ObjectId Id { get; set; }
public NodeType Type { get; set; }
}

private async static Task Main(string[] args)
{
var _database = new MongoClient("mongodb://localhost").GetDatabase("test");

await GetCollection<Node>().InsertOneAsync(new Node { Type = NodeType.Start });

IMongoCollection<T> GetCollection<T>() where T : class
{
return _database.GetCollection<T>(typeof(T).Name);
}

IMongoQueryable<TModel> Get<TModel>() where TModel : class
{
return GetCollection<TModel>().AsQueryable();
}

async Task<TModel> FindOneAsync<TModel>(Expression<Func<TModel, bool>> predicate) where TModel : class
{
var foundEntity = await Get<TModel>().FirstOrDefaultAsync(predicate);
if (foundEntity == null)
{
throw new Exception("not found");
}
return foundEntity;
}

var res = await FindOneAsync<Node>(node => node.Type == NodeType.Start);
}
}
}

关于C# Mongo - Linq 按枚举过滤 -> 转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57867682/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com