mongodb api_Net Core API MongoDB和事务入门

mongodb api

MongoDB is a kind of NoSQL database. NoSQL is a document-oriented database that is organized as a JSON. Some points about MongoDB:

MongoDB是一种NoSQL数据库。 NoSQL是组织为JSON的面向文档的数据库。 有关MongoDB的一些要点:

  • Performance: It stores a majority of data in RAM, so the query performance is much better here than in a relational database. But it requires more RAM and precise indexes.

    性能 :它将大多数数据存储在RAM中,因此此处的查询性能比关系数据库要好得多。 但是它需要更多的RAM和精确的索引。

  • Simplicity: Some users consider the query syntax is simpler here than in relational databases. The installation, configuration, and execution are simple and quick to do. And the learning curve is shorter than in the others.

    简单性 :一些用户认为这里的查询语法比关系数据库中的查询语法更简单。 安装,配置和执行非常简单快捷。 而且学习曲线比其他曲线短。

  • Flexibility: It’s dynamic because it doesn’t have a predefined schema.

    灵活性 :它是动态的,因为它没有预定义的架构。

  • Scalability: It uses shards for horizontal scalability, which makes it easier to increase storage capacity.

    可伸缩性 :它使用分片实现水平可伸缩性,从而更容易增加存储容量。

  • Transaction: v3.6 and beyond allow using the transaction concept. And v4.0 and beyond allow using the multi-document transaction concept.

    交易 :v3.6及更高版本允许使用交易概念。 v4.0及更高版本允许使用多文档交易概念。

Now that you know a little more about MongoDB, let’s go to our goal! This article proposes to teach you how you can build a .NET Core API connecting with MongoDB and use the Transactions with Dependency Injection.

现在,您对MongoDB有了更多了解,让我们开始我们的目标! 本文建议教您如何构建与MongoDB连接的.NET Core API以及如何使用带有依赖项注入的事务。

#ShowMeTheCode! (#ShowMeTheCode!)

For this example, don’t consider the structure and the architecture, it was built in this way just because I think that it’s easier to explain. So, I won’t explain the layers, folders, and other things in detail, except those needed by the use of MongoDB and the transactions.

对于此示例,不要考虑其结构和体系结构,而是因为我认为它更易于解释而以这种方式构建。 因此,除了使用MongoDB和事务所需的内容之外,我不会详细解释层,文件夹和其他内容。

该项目 (The project)

In this case, I used the Visual Studio 2019, Community version. So, with the VS installed, we select the “ASP.NET Core Web Application” option and select the API type.

在这种情况下,我使用了Visual Studio 2019社区版本。 因此,在安装了VS之后,我们选择“ ASP.NET Core Web应用程序”选项并选择API类型。

Image for post
Image for post

关于基础结构 (About the base structure)

After creating the project, we create five folders like below:

创建项目后,我们将创建五个文件夹,如下所示:

Image for post
  • Controllers: responsible to answer the requests

    管制员:负责回答要求
  • Entities: Domain classes

    实体:领域类
  • Interfaces: like contracts, we’ll use it to do the DI and IoC

    接口:像合同一样,我们将用它来进行DI和IoC
  • Models: Classes that we’ll use to receive and return data on controllers

    模型:我们将用于在控制器上接收和返回数据的类
  • Repositories: Classes with methods that contain the implementation of MongoDB operations

    仓库:带有包含实现MongoDB操作的方法的类

We’ll focus on just Controllers and Repositories folders and the Startup class. If you want to see the complete code, wait for the end of this article.

我们将只关注Controllers和Repositories文件夹以及Startup类。 如果您想查看完整的代码,请等待本文的结尾。

安装和配置MongoDB (Installing and configuring MongoDB)

Now, we need to install the more important package for our project, that is the MongoDB.Driver.

现在,我们需要为项目安装更重要的软件包,即MongoDB.Driver。

Image for post

After installed, we need to modify the Startup class, on the ConfigureServices method, specifically.

安装完成后,我们需要专门在ConfigureServices方法上修改Startup类。

Let’s analyze this code:

让我们分析一下这段代码:

The ConfigureServices method is where we do our IoC. So, the first statement is where we make the MongoDB connection. Pay attention in this step because we make a Singleton, we do this because the MongoClient instance, in MongoDB, is already a pool connection, so if you don’t use a Singleton, a new pool connection will always be created.

IoC是执行ConfigureServices方法的地方。 因此,第一个语句是我们建立MongoDB连接的位置。 在此步骤中要注意,因为我们创建了一个Singleton,我们这样做是因为MongoDB中的MongoClient实例已经是一个池连接,因此,如果您不使用Singleton,则将始终创建一个新的池连接。

And the second statement is where we declare the IoC, which we’ll use to start a session of the MongoDB Transaction. Notice that, in this case, we make a Scoped, because the transaction life cycle will be equal to the request life cycle.

第二条语句是声明IoC的位置,我们将使用该IoC来启动MongoDB Transaction的会话。 请注意,在这种情况下,我们将其设为“范围”,因为事务生命周期将等于请求生命周期。

创建基础存储库 (Creating a base repository)

So now, let’s make a base repository that we will use whenever we want to do some operations. First, the base repository class will receive a Generics <T> to identify the entity in our code that represents a collection in the database, like below:

现在,让我们建立一个基础存储库,在我们需要进行某些操作时将使用它。 首先,基础存储库类将收到泛型<T>,以标识代码中代表数据库中集合的实体,如下所示:

After creating the class, let’s go to declare some attributes that will be important to us:

创建完类后,让我们声明一些对我们很重要的属性:

We have four attributes:

我们有四个属性:

  • DATABASE: it’s the Constant that represents the name of our database.

    DATABASE :代表我们数据库名称的常量。

  • _mongoClient: it’s the client interface to MongoDB. Using it we do some operations on the database.

    _mongoClient :这是MongoDB的客户端接口。 使用它,我们对数据库进行一些操作。

  • _clientSessionHandle: it’s the interface handle for a client session. So, if you start a transaction, you should pass the handle when you do some operation.

    _clientSessionHandle :这是客户端会话的接口句柄。 因此,如果启动事务,则在执行某些操作时应传递句柄。

  • _collection: it’s the name of the collection used by the Generic class.

    _collection :这是Generic类使用的集合的名称。

All these attributes will receive a value on a class constructor:

所有这些属性将在类构造函数上收到一个值:

Look at the constructor parameters. We receive these parameters by dependency injection. We get the values of parameters and we assign them to the attributes that we created.

查看构造函数参数。 我们通过依赖注入接收这些参数。 我们获取参数的值,并将其分配给我们创建的属性。

Another very important thing is the code below of the assignments. If you work with transactions, on MongoDB, and work with a multi-document transaction, we need to create the collection first of all. And for it, we verify if the collection exists in our database and, if not, we create it. If we try to create a collection that already exists, the flow will break and throw an exception.

另一个非常重要的事情是赋值下面的代码。 如果您在MongoDB上处理事务,并在多文档事务中工作,那么我们首先需要创建集合。 为此,我们验证集合是否存在于我们的数据库中,如果不存在,则创建它。 如果我们尝试创建一个已经存在的集合,则流程将中断并引发异常。

Now, we will do an important code too, specifically a virtual property that we use to facilitate to do some operations:

现在,我们还将做一个重要的代码,特别是我们用来促进某些操作的虚拟属性:

From the _mongoClient attribute, we retrieve the database and, from the _collection attribute, we retrieve the collection and associate it with the Generic class.

_mongoClient属性,我们检索数据库,从_collection属性,我们检索集合并将其与Generic类关联。

Finally, we build some base operations to change the data in the database like Insert, Update, and Delete:

最后,我们构建一些基本操作来更改数据库中的数据,例如插入,更新和删除:

Some important things:

一些重要的事情:

  • We have to pass the _clientSessionHandle for all the methods that do, in fact, the operation, like the InsertOneAsync method.

    实际上,我们必须为所有执行操作的方法(如InsertOneAsync方法)传递_clientSessionHandle。

  • To do an Update operation, we build a Lambda Expression, using the ID property. And then, we use a Reflection to retrieve the ID value and we make the filter that will use to do, in fact, the operation.

    要执行更新操作,我们使用ID属性构建Lambda表达式。 然后,我们使用反射来获取ID值,并制作实际上将用于执行操作的过滤器。

特定存储库的示例 (Example of a specifical repository)

Now I show you how we can use the Base Repository to do some other specifically repository. In this case, we’ll build an AuthorRepository.

现在,我向您展示如何使用基本存储库来执行其他一些特定的存储库。 在这种情况下,我们将构建一个AuthorRepository。

First, we build the class with the inheritances and the constructor:

首先,我们使用继承和构造函数构建类:

When we inherit the BaseRepository class, we force it to make a constructor as shown. Look at how we pass the collection name using a string “author”.

当我们继承BaseRepository类时,我们强迫它创建一个如图所示的构造函数。 看看我们如何使用字符串“ author”传递集合名称。

Finally, we build some other MongoDB operations, here we build only specific query operations to get data. It happens because we can get specific data in each moment, but the operations that change the database data (like insert, update, delete) will be always the same in this example.

最后,我们构建其他MongoDB操作,在这里我们仅构建特定的查询操作来获取数据。 发生这种情况是因为我们可以随时获取特定的数据,但是更改数据库数据的操作(例如插入,更新,删除)在此示例中将始终相同。

In this code, I show you some query operations examples:

在这段代码中,我向您展示了一些查询操作示例:

  • We can recover one author searching by id.

    我们可以找一位按ID搜索的作者。
  • We can recover all authors.

    我们可以找回所有作者。
  • We can recover all books of a specific author, searching by author’s id, using the Project method.

    我们可以使用Project方法按作者ID检索特定作者的所有书籍。

  • We can recover some authors searching by name.

    我们可以找回一些按名称搜索的作者。

带有交易的业务规则示例 (Business rules examples with transactions)

Let’s use these repositories to do some business rules and use, in fact, the transactions! For this, we’ll make all business rules in the classes located in the Controller folder.

让我们使用这些存储库来制定一些业务规则,并使用事实上的交易! 为此,我们将在Controller文件夹中的类中创建所有业务规则。

So, we build a class called BusinessController, like below:

因此,我们构建了一个名为BusinessController的类,如下所示:

I’ll don’t talk about the Annotations and the inheritances class, because it’s specific for the API. So, look that we use the repositories that we created before and a session _clientSessionHandle that we’ll use to make the transactions. All these attributes we’ll receive on the constructor parameters by dependency injection.

我不会谈论注解和继承类,因为它专用于API。 因此,请看我们使用了之前创建的存储库以及用于进行事务处理的会话_clientSessionHandle。 我们将通过依赖注入在构造函数参数上接收所有这些属性。

So now, let’s show how we can use a transaction, in fact:

现在,让我们展示一下如何使用事务:

In this case, it’s a POST method, which means that we want to insert a new record on the database. In the method beginning, we need to start a transaction (line 11), then we can make our business rules and, if there is nothing wrong, we can Commit all changes we did on the database. But if something break, an exception will be thrown and the flow will begin on the Catch statement, thereby, we’ll abort all the transaction and nothing in the database will be changed.

在这种情况下,它是POST方法,这意味着我们要在数据库上插入新记录。 在开始的方法中,我们需要启动一个事务(第11行),然后可以制定业务规则,如果没有错误,则可以提交对数据库所做的所有更改。 但是,如果发生问题,将引发异常,并且流程将从Catch语句开始,因此,我们将中止所有事务,并且数据库中的任何内容都不会更改。

Below you can look another example using multi-document transactions. Where we use more than one operation on the database:

您可以在下面查看使用多文档交易的另一个示例。 在数据库上使用多个操作的地方:

The logic is the same as the code shown before.

逻辑与前面显示的代码相同。

Image for post

I expect that you liked this article! If yes, give a like to it. If you have any doubt or any questions comment below.

我希望您喜欢这篇文章! 如果是,给个喜欢。 如果您有任何疑问或疑问,请在下面评论。

You can find the complete code here!

您可以在此处找到完整的代码!

Thank you!

谢谢!

翻译自: https://medium.com/@alexalvess/getting-started-with-net-core-api-mongodb-and-transactions-c7a021684d01

mongodb api

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值