我有以下模型:
public class Student
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
还有我 Controller 中的这个端点:
public IEnumerable<Student> GetAll()
{
MongoCollection<Student> collection = Db.GetCollection<Student>("students");
List<Student> students = collection.AsQueryable().ToList();
return students;
}
向公众公开的 GetAll() 端点返回一个 Student,其 Id 类型为 ObjectId,这不是标准类型。我宁愿希望它是字符串类型。
但是如果我将其更改为字符串,我将无法使用 .ToList(),出现如下错误:
“无法从 BsonType ObjectId 反序列化字符串”
我知道我可以使用一些投影和转换来解决这个问题,但是它们会在 CRUD 方法中添加一些丑陋和嘈杂的代码。
保持 字符串类型的 Id 公开并仍然能够使用 c# 驱动程序的 api 的最佳方法是什么?
最佳答案
Controller 应该进行转换。通常, Controller 应该使用 DTO 与外界通信:
public IEnumerable<StudentReadDTO> GetAll()
{
MongoCollection<Student> collection = Db.GetCollection<Student>("students");
List<Student> students = collection.AsQueryable().ToList();
return students.Select(p => AutoMapper.Mapper.DynamicMap<StudentReadDTO>(p));
}
// this DTO should be used for POST and PUT (i.e where there is no id or the id
// is part of the URL) - after all, it doesn't make sense to send the id from the
// client to the server
public class StudentDTO
{
public string Name { get; set; }
}
// this should be used by reading operations, where the id is read from the server
// inheritance in DTOs is a source of confusion and can be painful, but this trivial
// type of inheritance will be fine
public class StudentReadDTO : StudentDTO
{
public string Id { get; set; }
}
此示例使用 AutoMapper在 Student
和 StudentDTO
之间进行基于约定的映射,但如果您愿意,可以自己进行映射。
在数据库层,使用ObjectId
是有意义的,因为its properties.
关于c# - MongoDB C# 驱动程序 - 从 Controller 返回字符串类型的 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28511391/