gpt4 book ai didi

c# - 通过 LUUID 获取文档

转载 作者:可可西里 更新时间:2023-11-01 09:18:32 25 4
gpt4 key购买 nike

我得到了一个非常简单的 .net 核心应用程序,它使用 REST 在 mongo db 中添加和下载对象。添加项目非常有效。获取包含所有项目的列表,但是当我尝试使用 id 访问一个列表时,每次我都得到 null我应该更改什么才能使这段代码正常工作。这意味着当数据库中有一个匹配项时,使用它的唯一 ID 从数据库中获取一个 Tool 对象。

这是数据库中的一个对象 database view这是我的存储库类

private IMongoCollection<Tool> Tools => _database.GetCollection<Tool>("Tools");

public async Task<Tool> GetAsync(Guid id) =>
await Tools.AsQueryable().FirstOrDefaultAsync(tool => tool.Id == id);

当我在调试器 "{ee1aa9fa-5d17-464c-a8ba-f685203b911f}" 中检查时,参数看起来像这样

编辑

工具类属性

public Guid Id { get; protected set; }

public string Model { get; protected set; }

public string Brand { get; protected set; }

public string Type { get; protected set; }

public uint Box { get; protected set; }

修复检查评论

Project on github

最佳答案

在 C# MongoDB 驱动程序中执行此操作的最简单方法是设置全局 GuidRepresentation 设置,该设置可以在 BsonDefaults 对象上找到。这是一个全局设置,将影响 GUID 到 Bson 二进制对象的所有序列化/反序列化。

BsonDefaults.GuidRepresentation = GuidRepresentation.PythonLegacy;

var collection = new MongoClient().GetDatabase("test").GetCollection<ClassA>("test");

var item = collection.Find(x => x.MyId == new Guid("ee1aa9fa-5d17-464c-a8ba-f685203b911f"))
.FirstOrDefault();

第二个选项是手动将 GUID 从 LUUID 转换为 CSUUID,为此在 GuidConverter 的 MongoDB 驱动程序中有一个辅助类,它可以将 GUIDbyte[] 中,它通常用于存储,但我们可以将其用于我们的查询。

BsonDefaults.GuidRepresentation = GuidRepresentation.CSharpLegacy;

var collection = new MongoClient().GetDatabase("test").GetCollection<ClassA>("test");

var luuid = new Guid("0798f048-d8bb-7048-bb92-7518ea4272cb");
var bytes = GuidConverter.ToBytes(luuid, GuidRepresentation.PythonLegacy);
var csuuid = new Guid(bytes);

var item = collection.Find(x => x.MyId == csuuid)
.FirstOrDefault();

我还注意到您正在使用 Robo 3T(以前称为 Robomongo),在此应用程序中,您可以通过转到 Options -> Legacy UUID Encodings 来设置 GUID 的显示方式>

RoboMongo

关于c# - 通过 LUUID 获取文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45738423/

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