获取LUUID的文档

时间:2017-08-17 14:51:02

标签: c# .net mongodb

我有一个非常简单的.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

1 个答案:

答案 0 :(得分:10)

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

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驱动程序中有一个帮助器类,它将GUID转换为{ {1}}通常用于存储,但我们可以将其用于查询。

byte[]

我还注意到您正在使用Robo 3T(以前称为Robomongo),在此应用程序中,您可以通过转到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(); - &gt;来设置GUID的显示方式。 Options

RoboMongo