MongoDB ODataController获取方法
问题描述:
如何将ObjectId传递到ODataController GET方法中?MongoDB ODataController获取方法
由于ObjectId存在文档的唯一标识符,我首先想到的是做这样的事情,其中“542978c4e4b0e67da1edc7f3”是的ObjectId:
odata/Teams(542978c4e4b0e67da1edc7f3)
但是当我这样做,我GET方法不不挑这件事,该ObjectId存在空{} 000000000000000000000000:
public Team GetTeam(ObjectId id)
{
var teams = mongoDatabase.GetCollection("Teams");
var team = teams.FindOneById(id);
....
我只是刚刚开始使用MongoDB的,什么是该做的正确的方式,还是我完全使用了错误的方法呢?
答
您可能需要在这里查看教程http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataServiceSample/ODataService。似乎你缺少[FromODataUri]作为输入参数。
答
这应该工作:
[EnableQuery]
public IHttpActionResult GetTeam([FromODataUri] string id)
{
var teams = mongoDatabase.GetCollection("Teams");
// convert the string 'id' to BsonValue 'bsonId'
......
var team = teams.FindOneById(bsonId);
// convert 'team' to the entity type Team object 'team'
......
return Ok(team);
}
然后通过查询设置的实体:
GET odata/Teams('542978c4e4b0e67da1edc7f3')
为OData的URL支持字符串作为参数。
将字符串'id'转换为BsonValue'bsonId'的正确语法是什么? – user517406 2014-10-12 10:25:14
@ user517406只是“BsonValue bsonValue = id;” – 2014-10-13 01:54:17