如何在 C# 中将字符串转换为 LiteDb.ObjectId,反之亦然
How to convert string to LiteDb.ObjectId and vise versa in c#
public class TaskModel
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }
}
public class TaskViewModel
{
public string Id { get; set; }
public string Name { get; set; }
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<TaskViewModel, TaskModel>()
.ForMember(dest=>dest.Id,opt=>opt.MapFrom(src=>src.Id));
CreateMap<TaskModel,TaskViewModel>()
.ForMember(dest=>dest.Id,opt=>opt.MapFrom(src=>src.Id));
}
}
[Route("api/[controller]/[action]")]
[ApiController]
public class TaskController : ControllerBase
{
// POST: api/Task/Post
[HttpPost]
public IActionResult Post([FromForm] TaskViewModel taskViewModel)
{
taskModel.Id = taskViewModel.Id; //ERROR: Connot implicitly convert 'string' to 'LiteDB.ObjectId'
taskModel.Name = taskViewModel.name
}
}
我有 LiteDB.ObjectId = 602f9484a5a84e0bc31938a8,所以我需要将 LiteDB.ObjectId 转换为字符串,反之亦然。
预先感谢您的帮助。
试试这个
将字符串转换为 ObjectId
taskModel.Id = new ObjectId (taskViewModel.Id);
将 ObjectId 转换为字符串
var id = taskModel.Id.ToString();
public class TaskModel
{
[BsonId]
public ObjectId Id { get; set; }
public string Name { get; set; }
}
public class TaskViewModel
{
public string Id { get; set; }
public string Name { get; set; }
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<TaskViewModel, TaskModel>()
.ForMember(dest=>dest.Id,opt=>opt.MapFrom(src=>src.Id));
CreateMap<TaskModel,TaskViewModel>()
.ForMember(dest=>dest.Id,opt=>opt.MapFrom(src=>src.Id));
}
}
[Route("api/[controller]/[action]")]
[ApiController]
public class TaskController : ControllerBase
{
// POST: api/Task/Post
[HttpPost]
public IActionResult Post([FromForm] TaskViewModel taskViewModel)
{
taskModel.Id = taskViewModel.Id; //ERROR: Connot implicitly convert 'string' to 'LiteDB.ObjectId'
taskModel.Name = taskViewModel.name
}
}
我有 LiteDB.ObjectId = 602f9484a5a84e0bc31938a8,所以我需要将 LiteDB.ObjectId 转换为字符串,反之亦然。 预先感谢您的帮助。
试试这个
将字符串转换为 ObjectId
taskModel.Id = new ObjectId (taskViewModel.Id);
将 ObjectId 转换为字符串
var id = taskModel.Id.ToString();