我有一个非常直接的.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);
Run Code Online (Sandbox Code Playgroud)
当我在调试器中检查时,参数看起来像那样 "{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; }
Run Code Online (Sandbox Code Playgroud)
修正了检查评论
Kev*_*ith 18
在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();
Run Code Online (Sandbox Code Playgroud)
第二个选项是手动将GUID从LUUID转换为CSUUID,为此在MongoDB驱动程序中有一个帮助器类GuidConverter,它将转换为通常用于存储的GUIDin,byte[]但我们可以将它用于查询.
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();
Run Code Online (Sandbox Code Playgroud)
我还注意到你正在使用Robo 3T(以前称为Robomongo),在这个应用程序中你可以通过Options- > 设置GUID的显示方式Legacy UUID Encodings
| 归档时间: |
|
| 查看次数: |
4875 次 |
| 最近记录: |