草庐IT

c# - 无法在 MongoDB Web API 中按 ID 获取文档

coder 2023-11-05 原文

我的 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.");
    }

模型:

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 服务:

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

对代码量表示歉意。我不确定为什么我能够获得我收藏中的第一份文件,但其他文件都没有。我感觉我的代码中存在序列化问题,或者我的 _id 嵌套在每个文档中?

最佳答案

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

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

注意事项:

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

关于c# - 无法在 MongoDB Web API 中按 ID 获取文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178810/

有关c# - 无法在 MongoDB Web API 中按 ID 获取文档的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  3. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  4. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  5. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  6. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  7. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  8. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  9. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  10. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

随机推荐