Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a document by LUUID

Tags:

c#

.net

mongodb

I got an .net core application that is pretty straight forward it is using REST to add and download objects to and from mongo db. Adding items works really well. Getting a list that contains all items aswell, but when I try to access one using id then everytime I get null. What should i change to make this piece of code work. It means get a Tool object from database using it unique ID when there's one matching in database.

Here's a object in database database view Here's my repository class

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

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

Argument looks like that when I check it out in debugger "{ee1aa9fa-5d17-464c-a8ba-f685203b911f}"

Edit

Tool Class Properties

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; }

Fixed check comments

Project on github

like image 825
karoluS Avatar asked Aug 17 '17 14:08

karoluS


1 Answers

The easiest way to do this in C# MongoDB Driver is to set a global GuidRepresentation setting which can be found on the BsonDefaults object. This is a global setting and will effect all serialization/deserialization of GUIDs in to Bson Binary Objects.

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();

The second option is to convert the GUID manually from a LUUID to a CSUUID, for this there is a helper class within the MongoDB driver of GuidConverter, with this it converts the GUID in to byte[] which is normally used for storage but we can use it for our query.

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();

I also noticed that you're using Robo 3T (formerly Robomongo), within this application you can set how GUIDs are displayed by going to Options -> Legacy UUID Encodings

RoboMongo

like image 50
Kevin Smith Avatar answered Nov 02 '22 08:11

Kevin Smith