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