c# - MongoDB C# 驱动程序 - 从 Controller 返回字符串类型的 Id

标签 c# mongodb

我有以下模型:

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

此示例使用 AutoMapperStudentStudentDTO 之间进行基于约定的映射,但如果您愿意,可以自己进行映射。

在数据库层,使用ObjectId 是有意义的,因为its properties.

关于c# - MongoDB C# 驱动程序 - 从 Controller 返回字符串类型的 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28511391/

相关文章:

c# - 旋转整数的数字

c# - 在任务栏中实现单独的应用程序实例,如 Skype

node.js - 在单个响应中返回 Mongoose 错误列表

node.js - 如何在 Mongo 中为数组的元素定义唯一索引

c# - Azure AD 上传服务主体 key 凭据证书

c# - 在 C# 中,如何将 XmlNode 转换为带有缩进的字符串? (没有循环)

c# - 第三方与 System.Net.Mail.SmtpClient

java - 如何让MongoDB服务可用?

mongodb - 在 Sitecore xDB 中存储自定义临时数据

javascript - 获取mongoDB模型树结构中的所有父文档