【问题标题】:Get last record using C# MongoDB driver使用 C# MongoDB 驱动程序获取最后一条记录
【发布时间】:2020-01-03 15:27:21
【问题描述】:

我正在为 API 使用 mongo 驱动程序。我的数据库的名称是“EventsDb”。我需要插入一个我拥有的实体,即“事件”。我需要返回 mongo db 的最后一个寄存器:

        T IRepository<T>.Add(T entity)
        {
            try
            {
                this.mongoCollection.InsertOne(entity);
                var response = this.mongoCollection.Find<Event>("EventsDb").limit(1).sort();
                return response;

            }
            catch (Exception e)
            {
                throw new NotImplementedException(e.ToString());
            }
        }

这是我遇到的问题:

严重性代码描述项目文件行抑制状态

错误 CS1929 'IMongoCollection' 不包含 “查找”和最佳扩展方法重载 'IMongoCollectionExtensions.Find(IMongoCollection, FilterDefinition, FindOptions)' 需要接收器类型 'IMongoCollection' Events.Repositories

如何解决这个错误?

【问题讨论】:

  • 你为什么要从已经实现的方法中抛出NotImplementedException
  • 现在只是为了证明,我仍然没有实现正确的异常,但问题不存在
  • 我知道问题不存在。这部分代码没有多大意义。
  • 这能回答你的问题吗? MongoDB and C# Find()
  • 您需要使用过滤器来使用 Find 或 lambda 表达式

标签: c# mongodb


【解决方案1】:

这是我对这个问题的解决方案,我添加了一个库

using MongoDB.Driver.Linq;

之后

    public T Add(T entity)
    {
        try
        {
            this.mongoCollection.InsertOne(entity);
            var response = this.mongoCollection.AsQueryable().OrderByDescending(c => c.Id).First();
            return response;
        }
        catch (Exception e)
        {
            throw new NotImplementedException(e.ToString());
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2021-12-26
    • 2015-01-29
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多