无法通过MongoDB Web API中的ID获取文档

时间:2017-05-25 10:55:38

标签: c# mongodb asp.net-web-api

我的Get请求允许我通过ID获取我的集合中的第一个文档,但不允许我通过ID获取任何其他文档,因此它只返回ID或null的第一个文档。我还有一个GetAll请求来返回我的数据库中的所有1000个文档,这似乎有效。

这是我的代码:

在Controller中获取请求:

 // GET api/something/id
    [HttpGet]
    public HttpResponseMessage Get(string id)
    {

        var something = _somethingService.Get(id);
        if (something != null)
        {
            return Request.CreateResponse(HttpStatusCode.OK, something);

        }
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Nothing for provided id.");
    }

Somethings Model:

public class SomethingsModel
{
    [BsonElement("_id")]
    [BsonRepresentation(BsonType.String)]
    public ObjectId id { get; set; }

    public string SomethingId
    {
        get { return id.ToString(); }
        set { id = ObjectId.Parse(value); }
    }

    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("description")]
    public string Description { get; set; }
    //[BsonElement("category")]
    //public string Category { get; set; } 

    [BsonElement("address")]
    public AddressModel Address { get; set; }

    [BsonElement("latlong")]
    public LatLongModel LatLong { get; set; }

    [BsonElement("price")]
    public int Price { get; set; }

    [BsonElement("rating")]
    public int Rating { get; set; }

    [BsonElement("photourl")]
    public string PhotoUrl { get; set; }

}

Somethings Service:

 public class SomethingService : ISomethingService
{
    private readonly SomethingsUnitOfWork _sUnitOfwork;

    public SomethingService()
    {
        _sUnitOfwork = new SomethingsUnitOfWork();
    }

    public SomethingsModel Get(string id)
    {
        return _sUnitOfwork.Somethings.Get(id);
    }

    public IQueryable<SomethingsModel> GetAll()
    {
        return _sUnitOfwork.Somethings.GetAll();
    }

    public void Delete(string id)
    {
        _sUnitOfwork.Somethings.Delete(s => s.SomethingId, id);
    }

    public void Insert(SomethingsModel something)
    {
        _sUnitOfwork.Somethings.Add(something);
    }

    public void Update(SomethingsModel something)
    {
        _sUnitOfwork.Somethings.Update(s => s.SomethingId, something.SomethingId, something);
    }

}

SoemthingsRepository:

public class SomethingsRepository<T> where T : class
{
    private MongoDatabase _database;
    private string _tableName;
    private MongoCollection<T> _collection;

    // constructor to initialise database and table/collection  
    public SomethingsRepository(MongoDatabase db, string tblName)
    {
        _database = db;
        _tableName = tblName;
        _collection = _database.GetCollection<T>(tblName);
    }


    /// <summary>
    /// Generic Get method to get record on the basis of id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public T Get(string id)
    {
        return _collection.FindOneById(id);

    }

    /// <summary>
    /// Get all records 
    /// </summary>
    /// <returns></returns>
    public IQueryable<T> GetAll()
    {
        MongoCursor<T> cursor = _collection.FindAll();
        return cursor.AsQueryable<T>();

    }

    /// <summary>
    /// Generic add method to insert enities to collection 
    /// </summary>
    /// <param name="entity"></param>
    public void Add(T entity)
    {
        _collection.Insert(entity);
    }

    /// <summary>
    /// Generic delete method to delete record on the basis of id
    /// </summary>
    /// <param name="queryExpression"></param>
    /// <param name="id"></param>
    public void Delete(Expression<Func<T, string>> queryExpression, string id)
    {
        var query = Query<T>.EQ(queryExpression, id);
        _collection.Remove(query);
    }

    /// <summary>
    ///  Generic update method to delete record on the basis of id
    /// </summary>
    /// <param name="queryExpression"></param>
    /// <param name="id"></param>
    /// <param name="entity"></param>
    public void Update(Expression<Func<T, string>> queryExpression, string id, T entity)
    {
        var query = Query<T>.EQ(queryExpression, id);
        _collection.Update(query, Update<T>.Replace(entity));
    }

}




And

我的文档架构:

{
"_id": {
    "$oid": "591593fbb2c2a737588dbbcc"
},
"name": "Kulas Inc",
"description": "Bypass Esophag to Duoden with Synth Sub, Perc Endo Approach",
"address": {
    "lineone": "9 Leroy Terrace",
    "city": "Afonsoeiro",
    "country": "Portugal",
    "postcode": "2870-013"
},
"latlong": {
    "latitude": "38.7",
    "longitude": "-8.9167"
},
"price": 61,
"rating": 70,
"photourl": "http://dummyimage.com/160x221.jpg/dddddd/000000"
}

代码量道歉。我不确定为什么我能够在我的收藏中获得第一个文件,但没有其他文件。我有一种感觉,我的代码中存在serilization的问题,或者我的_id是否嵌套在每个文档中?

1 个答案:

答案 0 :(得分:1)

您的实体的ID为ObjectId。从数据库中获取实体时,应使用此类型而不是字符串:

public T Get(string id)
{
    return _collection.FindOneById(ObjectId.Parse(id));
}

注意:

  • 默认情况下,您可以使用BsonClassMap的小写约定将所有元素存储为小写。
  • MongoDb使用_id名称作为身份字段。您无需手动指定它。
  • 您可以将方法的返回类型更改为IHttpActionResult,并使用ApiController中的OkNotFound方法创建相应的操作结果。