orm框架开发c#_软件开发中ORM框架的要点

orm框架开发c#

The extent of this post is generally speaking the whole ORM family running from different technology stacks. However, in this article, I will limit the explanation and samples only to C# programming language.

一般来说,这篇文章的范围是整个ORM系列,它们来自不同的技术堆栈。 但是,在本文中,我将解释和示例仅限于C#编程语言。

Image for post
Photo by Lucas Bellator on Unplash
Lucas BellatorUnplash上的 照片

After reading this article, you will be familiarized with the reasons why an ORM is an important piece on your Software Development. All the intentions will be supported by relevant technical details together-with the explanation of the benefits of why use an ORM.

一压脚提升阅读这篇文章,你会为什么一个ORM是软件开发的一个重要部分的原因而熟悉。 所有意图均会得到相关技术细节的支持,并解释了为什么使用ORM的好处。

This article is divided into 3 parts. First, I will explain the basic benefits of an ORM. Secondly, I will explain the important factors for you to understand the edge advantages of using an ORM. Lastly, I will explain the lower-level technicalities of how the ORM works behind the scene. This article is targeting everyone, but the latter sections are quite important if you are a Developer and/or Software Architect.

本文分为三个部分。 首先,我将解释ORM的基本好处。 其次,我将解释一些重要因素,以帮助您了解使用ORM的优势。 最后,我将解释ORM在后台如何工作的底层技术。 本文针对所有人,但是如果您是开发人员和/或软件架构师,则后面的部分非常重要。

Disclaimer: I am the author of RepoDb, therefore some of the samples on this article is specific to this ORM, but again, the rationale of this post is beyond the technology stack and library you are prefer to work with. Think of all the written samples as the code for your favorite ORM.

免责声明:我是RepoDb的作者,因此本文中的某些示例特定于此ORM,但同样,本文的基本原理超出了您更喜欢使用的技术堆栈和库。 将所有书面示例视为您喜欢的ORM的代码。

让我们从基础开始。 什么是ORM? (Let us Start with the Basics. What is an ORM?)

It has 2 meaning, one is for “mapper” as a framework, and the other one is for “mapping” as a concept.

它有两种含义,一种是将“映射”作为框架,另一种是将“映射”作为概念。

In the case of “mapper”, the ORM abbreviates the Object/Relational Mapper. It is a framework that you can embed within your application to manage the mapping of the database resultsets and the application class objects (vice-versa). The conversion applies even with or without the entity relationships.

在“映射器”的情况下,ORM缩写对象/关系映射器。 您可以将其嵌入应用程序中以管理数据库结果集和应用程序类对象的映射(反之亦然)。 即使有或没有实体关系,此转换也适用。

In the case of “mapping”, the ORM abbreviates the Object/Relational Mapping. It is the concepts that explains of how the ORM should work & behave, and how it is being implemented in overall. It also explains the high-level perspective of what ORM “as a mapper” is really about.

在“映射”的情况下,ORM缩写对象/关系映射。 正是这些概念解释了ORM应该如何工作和表现,以及总体上是如何实施的。 它还说明了“作为映射器” ORM真正涉及的高级观点。

Image below shows the high-level diagram of an Application Landscape with ORM.

下图显示了带有ORM的应用程序格局的高级图。

Image for post

Let us say, you made a query from the Customer table with the code below.

假设您是使用下面的代码从“客户”表中查询的。

SELECT Id, Name, Address FROM Customer WHERE Name = ‘John Doe’;

An ORM will then convert the result of the above query into a Customer class within your application. The selected columns Id, Name and Address will be mapped to the class properties named Id, Name and Address respectively. On the other hand, if you push a data towards the database, an ORM will map the properties of the class into the columns of the target table. The value will then be saved or updated accordingly based on these mappings.

然后,ORM会将上述查询的结果转换为您的应用程序中的Customer类。 选定的IdNameAddress列将分别映射到名为IdNameAddress的类属性 另一方面,如果将数据推向数据库,则ORM会将类的属性映射到目标表的列中。 然后,将根据这些映射相应地保存或更新该值。

As I am only explaining the basics, I would recommend to visit this article if you would like to understand further what is an ORM in both areas.

由于我只是在解释基本知识,因此,如果您想进一步了解这两个领域的ORM,建议您访问本文

#第1部分-好处 ✔️ (# Part 1 — The Benefits ✔️)

In this part, the sections covered are all about the benefits of ORM. The information written is in purpose to persuade you to consider using an ORM on your Software Development. Let us begin!

在本部分中,所涵盖的各个部分都是关于ORM的好处。 所写的信息旨在说服您考虑在软件开发中使用ORM。 让我们开始吧!

ORM does…

ORM确实…

1.提高您的开发敏捷性 (1. Improves your Development Agility)

Most ORM are packed with the necessary features in order for us to do the basic things. These features comes with different capabilities, addressing the use-cases from the different areas and/or domains. Same goes to your end, when you develop a Software Project, you are implementing its features and capabilities to address the use-cases requested by your customers.

大多数ORM都包含必要的功能,以便我们执行基本操作。 这些功能具有不同的功能,可以解决来自不同领域和/或领域的用例。 同样,开发软件项目时,您正在实现其功能,以解决客户要求的用例。

As ORM is designed to address the problem in the Data Access Layers, it then as well by-default addressing your own problem on that area by being a consumer of this framework. Imagine inheriting the certain numbers of features that does the job for you without you even writing a code for it, and that you are required to implement these features without an ORM.

由于ORM旨在解决数据访问层中的问题,因此默认情况下,它也会成为该框架的使用者,从而解决您在该领域的问题。 想象一下,继承某些可以为您完成工作的功能,而无需编写代码,甚至无需ORM即可实现这些功能。

A Data Access Layer is commonly known as Repository, the object that mediates the mapping layer of your application and your database

数据访问层通常称为“ 存储库” ,它是中介应用程序和数据库的映射层的对象

To be specific, querying a record from the database requires certain number of code, like below.

具体来说,从数据库查询记录需要一定数量的代码,如下所示。

And most of the code will be eliminated if with ORM, like below.

如果使用ORM,则大部分代码将被消除,如下所示。

No just that, by using an ORM, it also helps you write simple unit of code and with uniformity. All the methods and functions are contextually pre-given with the names equivalent to its purpose. Those making you more faster to implement the important methods needed for your business cases.

不仅如此,通过使用ORM,它还可以帮助您编写简单且统一的代码单元。 所有方法和功能均在上下文中预先赋予与其用途等效的名称。 这些使您更快地实施业务案例所需的重要方法。

I also would like to highlight the importance of ORM in the Microservice Architecture, commonly known as Microservices.

我还想强调一下ORM在微服务体系结构(通常称为微服务)中的重要性。

微服务架构 (Microservice Architecture)

Image for post
link 链接获取的

As you know, the Microservice Architecture is known to be the most popular Software Architectural Design nowadays. Majority of the companies tend to develop a micro component in relation to this architecture. It is because, by doing such thing, it would sustain the fast-changing demands of the customers. This does not limit whether the application is running “On-premise or Cloud”, “Windows or Linux” and/or etc.

如您所知,微服务架构是当今最受欢迎的软件架构设计。 大多数公司倾向于开发与此架构有关的微型组件。 因为这样做可以满足客户不断变化的需求。 这不限制应用程序是否正在运行“本地或云”,“ Windows或Linux”和/或其他。

Micro component — it is a single running service within the Microservice Architecture. It has its own state and is independent from the other components.

微型组件 -它是服务架构中的单个运行服务。 它具有自己的状态,并且独立于其他组件。

An ORM is predominantly important on this area. It is an edge-case where it is beneficial to you “the most” as it improves the agility of your development within each micro-component. By having it as a tool during your development, you will eliminate the effort of writing the fundamentals of your Data Access Layer. It also important to take note that an ORM can be utilized to all other components of your Microservice Architecture without even concerning about the versions and/or etc.

ORM在这方面至关重要。 这是一个极端案例,它“提高”了您的利益,因为它提高了每个微型组件内开发的敏捷性。 通过将其作为开发过程中的工具,您将无需编写数据访问层的基础知识。 还需要注意的是,ORM可以用于微服务体系结构的所有其他组件,而无需考虑版本和/或其他信息。

Without using an ORM, all the fundamentals of your repository must first be implemented in every micro-component, and with this, your development is much slower. On top of this, the code-base is much complex and larger than it is with ORM. Not to mention, your code will most likely be duplicated if being used to the other use-cases and/or micro-components, which is against the DRY principle.

在不使用ORM的情况下,必须首先在每个微型组件中实现存储库的所有基础知识,因此,您的开发速度将大大降低。 最重要的是,代码库比ORM复杂得多。 更不用说,如果您的代码被用于其他用例和/或微型组件,则很可能会被复制,这违反了DRY原则。

2.消除您的代码复杂性 (2. Eliminates your Code Complexity)

Image for post
link 链接获取的

In your application, you need a foundation of your Data Access Layers. By having a lower-level implementation of this area is an additional layer of complexity. Why not just utilize and leverage the ORM?

在您的应用程序中,您需要数据访问层的基础。 通过对该区域进行较低级别的实现,可以增加一层复杂性。 为什么不仅仅利用和利用ORM?

Imagine writing the full sets of C.R.U.D. operations with an average of 25 lines of code per operation. Whereas, writing it with ORM only takes 2 lines of code whilst accomplishing the same job. The difference is huge in relation to your effort.

想象一下,编写完整的CRUD操作集,每个操作平均需要25行代码。 而使用ORM编写它只需花两行代码即可完成相同的工作。 与您的努力有关,差异很大。

Below are the drawbacks (in specific area) you will be facing if you are not using an ORM in your Software Development.

如果您在软件开发中未使用ORM,则将面临以下缺点(在特定领域)。

  • Maintainability— your application is becoming more difficult to maintain as you are to implement the fundamentals of your repository. The lines of code is most likely double-in-size than the number of code you can write if with ORM. Always bare in mind, the more code you write, the harder the maintenance is.

    可维护性 —随着您实现存储库的基础知识,您的应用程序变得越来越难以维护。 代码行的大小很可能是使用ORM时可以编写的代码数的两倍。 切记,编写的代码越多,维护就越困难

  • Code Duplication — there is a higher chance that the code you write may be duplicated to accommodate other data models for different use-cases and/or different micro components.

    代码复制 -您编写的代码被复制的可能性更大,以适应不同用例和/或不同微组件的其他数据模型。

  • Re-usability — your code will most likely be not reusable from the other components of the Microservices. Other team may prefer a different style or standard of doing the “things” than you (or your team).

    可重用 -您的代码很可能无法从微服务的其他组件中重用。 与您(或您的团队)相比,其他团队可能更喜欢采用不同的样式或标准来做“事情”。

  • Extensibility — the code that you will write will mostly be closed for extensibility. It is because, without an ORM, you are also close to writing a code in relation to your own use-cases “without” thinking of the other use-cases. Though, “I am not generalizing this”.

    可扩展性 -您将要编写的代码通常会因可扩展性而关闭。 这是因为,如果没有ORM,您也接近编写与您自己的用例相关的代码,而不会“考虑”其他用例。 不过,“我没有对此进行概括”。

Most of the drawbacks mentioned above are related to the SOLID principle, a very important principle when writing a software application with Object-Oriented Programming paradigm. It is just an overkill to implement everything from scratch, even for just a simple Insert/Update operation. Try to eliminate the mentioned drawbacks during your Software Development by simply using an ORM.

上面提到的大多数缺点都与SOLID原理有关, SOLID原理是在编写带有面向对象编程范例的软件应用程序时非常重要的原理。 从头开始实现所有功能,甚至只是一个简单的插入/更新操作,都不过分。 尝试通过使用ORM消除软件开发过程中提到的缺点。

3.帮助您编写更少的代码并执行更多功能 (3. Helps You Write Lesser Code and Do More Features)

Though this could be an extension of the first item above, but it explain the things in a more detailed.

尽管这可能是上面第一项的扩展,但是它更详细地解释了这些内容。

An ORM, by default, mostly provides the initial features that accommodate the basic operations out-of-the-box. By using it, you are automatically inheriting all the those features. You also automatically skipped the tedious part of your Software Development pertaining to the Data Relational Management. Again, without using an ORM, you are responsible of building the fundamentals of your repository, which is quiet tedious in most cases.

默认情况下,ORM大部分提供了开箱即用的基本功能。 通过使用它,您将自动继承所有这些功能。 您还自动跳过了软件开发中与数据关系管理有关的繁琐部分。 同样,在不使用ORM的情况下,您有责任构建存储库的基础,这在大多数情况下是非常乏味的。

The time and effort you spent building the foundation of your Data Access Repository could somehow be utilized implementing the actual business requirements. Enabling you to instantly work with the actual use-cases that gives more value to the customers.

您花了一些时间和精力来建立数据访问存储库的基础,从而可以用来实现实际的业务需求。 使您能够立即使用实际用例,从而为客户带来更多价值。

To be specific, if you are to implement your own way, then below is the code for inserting a new Customer record via ADO.NET.

具体来说,如果您要实现自己的方式,则下面是通过ADO.NET插入新客户记录的代码。

While below are the code when using an ORM.

下面是使用ORM时的代码。

The code above only refers to Insert operation, a basic operation that saves a data into the database. Imagine the effort you are going to spent if you are to implement the following operations just to build the foundation of your repository.

上面的代码仅涉及插入操作,这是将数据保存到数据库中的基本操作。 想象一下,如果要实施以下操作只是为了建立存储库的基础,您将花费多少精力。

  • Read, Update, Delete operations— just to complete the C.R.U.D.

    读取,更新,删除操作-仅用于完成CRUD
  • Batch and Bulk operations

    批量和批量操作
  • Caching, Join operations

    缓存,联接操作
  • Many more here…

    这里还有更多……

In addition to that, what if your requirement is different in every entity model? Not to mention the requirements in every micro-component.

除此之外,如果您的要求在每个实体模型中都不相同怎么办? 更不用说每个微型组件的要求了。

ORM在存储库中的重要性 (The Importance of ORM in the Repository)

As repository is an integral part of your application, therefore it is important that this area is consistent and free-of-error. It is also best to make this area clean and simple (i.e.: lesser lines of code, simple unit of methods, etc).

由于存储库是应用程序不可或缺的一部分,因此确保该区域的一致性和无错误性非常重要。 最好使该区域干净整洁(即:更少的代码行,简单的方法单元等)。

In repository, you introduce all the necessary operations needed by your application (already mentioned above). So it is common to this area to move fast, as the new operations will be introduced in response to the new requirements requested. However, it is a big problem if you are to implement everything from scratch specially if you have the requirements that limits you make this area “generic” and “dynamic”.

在存储库中,您将介绍应用程序所需的所有必要操作(如上所述)。 因此,快速移动这个区域很常见,因为将根据要求的新要求​​引入新的操作。 但是,这是一个很大的问题,如果您要从头开始实施所有内容,特别是如果您有限制要使该区域“通用”和“动态”的要求,那么这是一个大问题。

Imagine, you are working with clustered environment and you introduce some operations on your repository to cater this use-case, specifically for the tables where the Primary Keys are Identities. Few weeks later, a new requirement is needed where you need to connect to a non-clustered environment and/or maybe creating a support to a non-identity table to the existing clustered environment. Then you introduce specialized operations to cater it. There you wrote multiple sets of code to cater multiple requirements. It is just too much for the preliminary work as it drags you completely to slowness.

想象一下,您正在使用集群环境,并且在存储库中引入了一些操作来满足此用例,特别是针对主键为标识的表。 几周后,在需要连接到非集群环境和/或可能需要为现有集群环境的非身份表创建支持的情况下,需要新的要求。 然后,您将介绍专门的操作来解决此问题。 在这里,您编写了多组代码来满足多种需求。 对于初步工作而言,这太多了,因为它使您完全陷入缓慢。

By having an ORM, you will skip all these preliminary work. You just have to leverage the built-in features like BaseRepository/DbContext and everything will just work like a charm, accomplishing the same job as your intention.

通过拥有ORM,您将跳过所有这些准备工作。 您只需要利用诸如BaseRepository / DbContext之类的内置功能,一切都将像魅力一样工作,完成您预期的工作。

That being said, using an ORM has a huge advantage when being compared to “not using an ORM at all”.

话虽如此,与“根本不使用ORM”相比,使用ORM具有巨大的优势。

4.涵盖您的维护责任 (4. Covers your Maintenance Responsibility)

One important factor of why choose an ORM over implementing your own is the advantage of “responsibility” in the maintenance.

为什么选择ORM而不是自己实施ORM的一个重要因素是维护中“责任”的优势。

Image for post
link 链接获取的

Do you prefer to fix the problems yourself? If yes, can you afford fixing the problems? If not, then use an ORM. Time is money, with ORM they do it for you for free.

您喜欢自己解决问题吗? 如果是,您能否负担解决这些问题的费用? 如果不是,则使用ORM。 时间就是金钱,有了ORM,他们可以免费为您服务。

As you know, ORM maintainers are there to dedicate their time fixing the problems pertaining to the Data Access Layers. This in short explain that you itself are leveraging their time fixing the problem for you, without asking for return. By having this privilege, you can just work directly on your business problems without worrying the other side of the coin.

如您所知,ORM维护人员在那里致力于解决与数据访问层有关的问题。 简而言之,这说明您自己正在利用他们的时间为您解决问题,而不要求退货。 通过拥有此特权,您可以直接处理业务问题,而不必担心硬币的另一面。

#第2部分-因素 ✔️ (# Part 2 — The Factors ✔️)

In this part, the covered sections are more about the important factors to consider for you to use an ORM. These factors will give you an edge advantages when an ORM is used on your Software Development. Let us begin!

在本部分中,涵盖的部分更多地是有关使用ORM时要考虑的重要因素。 当在软件开发中使用ORM时,这些因素将为您带来优势。 让我们开始吧!

ORM is…

ORM是…

1.更智能 (1. More Intelligent)

This factor is related to the internal-logic implied within the ORM over the logic that you can write when writing yours.

此因素与ORM中隐含的内部逻辑有关,而不是在编写逻辑时可以编写的逻辑。

You might didn’t know, most ORM understand the schema of your database. When you call any of the built-in operation, an ORM will most likely speak to your database to retrieve the necessary information pertaining to the schema of the target table. This is only happening once. The information is then saved in the memory of your computer, where the application runs.

您可能不知道,大多数ORM都了解数据库的架构。 当您调用任何内置操作时,ORM很可能会与您的数据库对话以检索与目标表的架构有关的必要信息。 这仅发生一次。 然后将信息保存在运行应用程序的计算机内存中。

By having such schema information, the ORM will use it to create an optimized compiled-function for your operation, giving you the most-performant and efficient method for future executions.

通过具有此类架构信息,ORM将使用它来为您的操作创建优化的编译函数,从而为您提供最高效,最有效的方法以供将来执行。

Disclaimer: I am not generalizing the above concepts to all ORM, but most ORM does it.

免责声明:我并没有将上述概念推广到所有ORM,但是大多数ORM都这样做。

This means that, without you knowing behind the scene, an ORM is executing a special logic implemented internally to give you the desired compiled-operations. These special logic are:

这意味着,在您不了解幕后的情况下,ORM正在执行内部实现的特殊逻辑,以为您提供所需的编译操作。 这些特殊逻辑是:

  • Ahead-of -Time (AOT) Compilation

    提前(AOT)编译
  • Skips the Database NULL-Checks

    跳过数据库的NULL检查
  • Column/Property Projection

    列/属性投影
  • Type Extraction/Conversion

    类型提取/转换
  • Cache Re-usability

    缓存可重用性

In the case of not using an ORM, you are most likely leaving the mentioned logic above behind, it is because you are only concentrating delivering your own business cases. Though, it is completely fine for as long you can afford implementing it, money and time wise. But it is highly recommended to utilize an ORM for you to leverage and inherit this package by default.

在不使用ORM的情况下,您很可能会将上面提到的逻辑留在后面,这是因为您只是专注于交付自己的业务案例。 不过,只要您能够负担得起实施它(金钱和时间),它就完全可以了。 但是,强烈建议您利用ORM来默认利用和继承此程序包。

2.表现更好 (2. More Performant)

This factor is related to the speed of the execution of an ORM, over the speed of the execution of your own implementation.

此因素与ORM的执行速度有关,而与您自己的实现的执行速度有关。

I often heard that if you would like to make it more-efficient and fast, then use the “raw” implementation. This statement is not truthful. There is no correct answer until you write the “perfect” code yourself.

我经常听到,如果您想使其更加高效和快速,请使用“原始”实现。 这句话是不真实的。 在您自己编写“完美”代码之前,没有正确的答案。

Image for post
link 链接获取的

Referring to performance, the main reason to this is the number of execution paths (aka branching points). In order for the application to be more performant, the number of execution path must be lessen. If you write your own fundamental implementation, you are most likely writing more lines of code. The more code you write, the more execution paths to execute, resulting to a slower application.

关于性能,其主要原因是执行路径 (也称为分支点)的数量。 为了使应用程序具有更高的性能,必须减少执行路径的数量。 如果您编写自己的基本实现,则很可能编写更多的代码行。 您编写的代码越多,执行的路径就越多,从而导致应用程序速度变慢。

As you know, ORM is built to address the real-world problem pertaining to RDBMS. As “performance” is a basic problem in this space, you can guarantee that this use-case is by default addressed by ORM in many ways. Mentioned in the previous section, ORM gives you the best ahead-of-time (AOT) compilation, NULL-checks and/or etc. With these techniques, the number of execution paths were most likely reduced to its lowest number possible.

如您所知,ORM旨在解决与RDBMS有关的现实问题。 由于“性能”是该领域的基本问题,因此您可以保证ORM默认以多种方式解决此用例。 在上一节中提到,ORM为您提供最佳的提前 (AOT)编译,NULL检查和/或其他方法。使用这些技术,执行路径的数量很可能减少到了可能的最低数量。

Note: A compiled code is difficult to read and maintain, therefore, the compilation is mainly used for library and framework only, like an ORM. You as a developer should not create a compiled-code during the Software Development to avoid the code-complexity.

注意:编译后的代码难以阅读和维护,因此,编译后的代码主要用于库和框架,例如ORM。 作为开发人员,您不应在软件开发过程中创建已编译的代码,以避免代码复杂。

Unless you are considering the mentioned techniques above while writing your own lower-level implementation, there is no way you can beat the ORM in terms of performance. Though, I will not generalize this to all good developers that could create the best code.

除非您在编写自己的较低级别的实现时考虑上述技术,否则就无法在性能方面击败ORM。 虽然,我不会将其推广到所有可以创建最佳代码的优秀开发人员。

You can read the detailed explanations in the latter part of this article.

您可以阅读本文后半部分的详细说明。

3.更高效 (3. More Efficient)

This factor is related to the efficiency of the code written in ORM when compared to the code that you can write.

与您可以编写的代码相比,此因素与ORM中编写的代码的效率有关。

Image for post
link 链接获取的

One of the most important factor to sustain the stability of your application is when it is efficient. Efficiency is referring to the “how” the computer memory is being utilized. The lower the consumption, the better.

保持应用程序稳定性的最重要因素之一就是效率。 效率是指计算机内存的“使用方式”。 消耗越少越好。

In general, if we accidentally have written a leaky code, it would result to a higher memory consumption in the application servers. Same goes to your end. The effect, your application may stop while in the middle of the operations.

通常,如果我们不小心编写了泄漏代码,则将导致应用程序服务器中的内存消耗增加。 同样也要结束。 效果是,您的应用程序可能在操作过程中停止。

Do you matter how the code is written in your end? I suppose not, so do to me. Though, I am not generalizing this.

您最后编写代码的方式是否重要? 我想不是,对我也是如此。 虽然,我没有对此进行概括。

To be specific, in C#, do you use string interpolation or the legacy low-level method like string.Contact()? Using a string interpolation allocates more memory than using the lower level implementation, so do for the other non-lower level implementations. It is a same question to the developers who are using the other programming language.

具体来说,在C#中,您使用字符串插值还是传统的低级方法,例如string.Contact() ? 与使用较低级别的实现相比,使用字符串插值分配的内存更多,对于其他非较低级别的实现也是如此。 对于使用其他编程语言的开发人员来说,这是一个相同的问题。

An ORM is always more efficient due to the information it got from your database, and also, the compilation techniques it utilizes when building the compiled functions. Not just that, a series of test is being performed to measure the memory usage before the actual production delivery.

由于ORM从数据库中获得的信息以及构建编译函数时所利用的编译技术,因此ORM总是效率更高。 不仅如此,正在执行一系列测试以测量实际生产交付之前的内存使用情况。

To support the claims, an ORM is most-likely a well-tested framework (end-to-end) with the tools provided by the community itself. This tool often called an ORM Bencher and is used to measure both the performance and efficiency of various ORM that is being used by the community. The good part here, through this tool, most ORM authors keeps improving the framework to be always on the top, which is a free benefit to you as a user.

为了支持这些主张,ORM最有可能是一个经过充分测试的框架(端对端),带有社区本身提供的工具。 该工具通常称为ORM Bencher ,用于衡量社区使用的各种ORM的性能和效率。 通过此工具的好处是,大多数ORM作者不断改进该框架,使其始终位于最顶层,这对您作为用户是免费的。

4.更高的质量 (4. Higher in Quality)

This factor is related to the stability of the code the ORM has over the customized code you can write.

这个因素与ORM在您可以编写的自定义代码上的代码稳定性有关。

It is important to know that most ORM comes with package of Unit and Integration Tests. These are covering the real-world scenarios and are used to guard the features written on the ORM. So that, any developer (like you) who is using an ORM is free of error.

重要的是要知道大多数ORM都带有单元测试和集成测试包。 这些涵盖了真实的场景,并用于保护ORM上编写的功能。 这样一来,使用ORM的任何开发人员(如您)都不会出错。

In addition, most ORM authors are continuously collecting the issues from the community, have those issues fixed by them and embed on the framework. After the fixes, a new dedicated tests suite will be written to guard the newly embedded scenarios.

此外,大多数ORM作者都在不断地从社区中收集问题,让他们自己解决这些问题并嵌入到框架中。 修复之后,将编写一个新的专用测试套件来保护新嵌入的方案。

In the case of usability, various developers (not just you) are using the same ORM framework, but in a different use-case. In that way, the ORM is also being tested beyond your own scenario.

就可用性而言,各种开发人员(不仅是您)正在使用相同的ORM框架,但使用的是不同的用例。 这样,还可以在您自己的场景之外对ORM进行测试。

I am trying explain the reality where the position of ORM really is. As most ORM is open-source, the community and handful of developers are directly improving it, making the framework more stable and capable of addressing certain use-cases.

我正在尝试解释ORM实际位置的现实。 由于大多数ORM是开源的,因此社区和少数开发人员都在直接对其进行改进,从而使该框架更加稳定并能够解决某些用例。

Do you usually do the mentioned activities above when writing your own implementation? If not, then that is being said, an ORM implementation is always more mature than your own implementation.

在编写自己的实现时,通常会执行上述活动吗? 如果不是,那么这就是说,ORM实现总是比您自己的实现更成熟。

Image for post
link 链接获取的

I am grateful that you made this far. You already have digested most of my intentions on this article in relation to ORM. However, it would be better if you can read further to understand the low-level explanation of the technical implementation behind the ORM as a framework.

我很高兴你能做到这一点。 您已经消化了我对本文有关ORM的大部分意图。 但是,最好能进一步阅读以理解对作为框架的ORM背后的技术实现的底层解释。

#第3部分-技术细节✔️ (# Part 3 — The Technicalities ✔️)

Further readings below will be specific to C# language (or .NET as a whole). I will explain the low-level technicalities of how the ORM is being implemented in .NET point-of-view.

以下进一步阅读内容将特定于C#语言(或整个.NET)。 我将解释在.NET角度如何实现ORM的底层技术。

In addition to this and being an author of an ORM, I will do explain and share the techniques that I used when implementing RepoDb. Though, most of the techniques I used are collective, conceptualized by me, colleagues and/or other ORM creators. To emphasize, most ORM are the same in technique, whether you use the ORM framework A over B, or whatever.

除此之外,作为ORM的作者,我将解释并分享实现RepoDb时使用的技术。 虽然,我使用的大多数技术都是集体的,是由我,同事和/或其他ORM创作者概念化的。 要强调的是,无论您是使用ORM框架A还是使用B框架,大多数ORM的技术都是相同的。

Note: Please bare in mind that I am blank whether the concepts to be discussed are present on the language that you are opt to use for Software Development.

注意:请记住,我是空白的,是否要讨论的概念是否存在于您选择用于软件开发的语言中。

1.提前(AOT)编译 (1. Ahead-of -Time (AOT) Compilation)

Ahead-of-Time (AOT) is a very low-level terminology which is common used in compiler.

提前(AOT)是非常低级的术语,在编译器中常用。

Ahead-of-Time (AOT) compilation is a concept applied when compiling an application code. It is a technique used to enhance the performance of the code execution by pre-compiling a function during the runtime and utilize it for future use.

提前(AOT)编译是在编译应用程序代码时应用的概念。 它是一种通过在运行时预编译功能并将其用于将来使用来增强代码执行性能的技术。

This compilation helps your application interacts with the lower-level code, commonly used as Intermediate Language, so it will be easily understood by the computer. The compiled code is resulted to a binary that is opt for the computer to understand and executed it natively, thus giving you a maximum performance when it comes to execution.

此编译可帮助您的应用程序与通常用作中间语言的较低级代码进行交互,因此计算机将很容易理解它。 编译后的代码将生成二进制文件,计算机可以选择该二进制文件来本地理解和执行它,从而在执行时为您提供最佳性能。

I would generally say, you are not doing a pre-compilation when writing your own code. It is just an overkill for you as a developer and as a maintainer. This technique only applies to a framework/library that is opt for everyone-to-use, not for a commercial Product or Software.

我通常会说,在编写自己的代码时,您没有进行预编译。 对于开发人员和维护人员来说,这只是一个过大的杀伤力。 该技术仅适用于可供所有人使用的框架/库,不适用于商业产品或软件。

2.跳过数据库的NULL检查 (2. Skips the Database NULL-Checks)

The DbDataReader.IsDbNull() method is known to be a slow method. In addition, by adding a condition that checks the class property NULL values is an additional execution path.

已知DbDataReader.IsDbNull()方法是一种缓慢的方法。 另外,通过添加检查类属性NULL值的条件,是一条附加的执行路径。

This is a a customized logic embedded to an ORM (not to all) that skips the unnecessary check when extracting a resultset back to a language native data type (vice versa).

这是一种嵌入到ORM(并非全部)中的自定义逻辑,在将结果集提取回一种语言本机数据类型时,它会跳过不必要的检查(反之亦然)。

To be specific, if you have a Customer table with 15 columns and 5 of the columns are required, then ORM are projecting those column to be excluded for NULL checking. Since ORM is speaking to your database when calling an operation, ORM knows how to project it automatically. Required columns are always having a value and by eliminating the NULL-check will improve the performance of the execution.

具体来说,如果您有一个包含15列和5列的Customer表,则ORM会将这些列投影为NULL检查排除在外。 由于ORM在调用操作时正在与您的数据库对话,因此ORM知道如何自动对其进行投影。 必需的列始终具有一个值,并且通过消除NULL检查将提高执行性能。

Though in general, you are most likely projecting that some columns of the table are already required and you do skipping it by default. But, we cannot do it perfectly to all cases (i.e.: all columns, all table, all components and/or use-cases).

尽管总的来说,您最有可能预测该表的某些列已经是必需的,并且您默认会跳过它。 但是,我们不能在所有情况下都做到完美(即:所有列,所有表,所有组件和/或用例)。

3.列/属性投影 (3. Column/Property Projection)

During the data extraction and transformation, ORM uses the class properties if the number is lower than the number of of table properties, otherwise it uses the table properties.

在数据提取和转换期间,如果数量少于表属性的数量,那么ORM将使用类属性,否则,它将使用表属性。

What do I mean by this? There is a case that your class object properties are not equal to the actual table columns, and with this, not all properties/columns can be mapped. When this happen, which is also a very basic use-case, ORM will identify whether the table columns or the class properties will be used for extraction. It then use that list in all execution paths, like…

我是什么意思 在某些情况下,您的类对象属性不等于实际的表列,因此无法映射所有属性/列。 发生这种情况( 这也是一个非常基本的用例)时 ,ORM将标识是将表列还是类属性用于提取。 然后,它将在所有执行路径中使用该列表,例如…

  • Iteration/Skipping

    迭代/跳过
  • Data Retrieval/Assignment

    数据检索/分配
  • Method Compilation

    方法编译
  • Etc

    等等

As mentioned many times, behind the scene, ORM is pre-touching your database to get the schema. With the information of the class properties and table columns, ORM knows what/which columns to project in all compilation. This projection eliminates the unnecessary compilation on the compiled-function, resulting to a much more efficient and performant execution.

正如许多次提到的那样,在幕后,ORM正在预触数据库以获取架构。 利用类属性和表列的信息,ORM知道在所有编译中要投影哪些/哪些列。 这种投影消除了对已编译函数的不必要编译,从而实现了更加高效和高效的执行。

4.类型提取/转换 (4. Type Extraction/Conversion)

The best way to extract a data from the DbDataReader is through Get<Type>() methods.

从DbDataReader提取数据的最佳方法是通过Get <Type>()方法。

Do you happen to always write code to use the Get<Type>() method of the DbDataReader? I would say, NOT.

您是否总是编写代码以使用DbDataReaderGet<Type>()方法? 我会说,不是。

By using that method is quietly tricky, it is not safe as well. Imagine you have the query below.

通过使用该方法非常棘手,它也不安全。 假设您在下面有查询。

SELECT Id, Name, Address FROM [dbo].[Customer];

And happen to write the equivalent C# code below.

碰巧在下面编写了等效的C#代码。

var list = new List<Customer>();
while (reader.Read())
{
var customer = new Customer();
customer.Id = reader.GetInt32(0);
customer.Name = reader.GetString(1);
customer.Address = reader.GetString(2);
customers.Add(customer);
}
return list;

The drawback to this is the data alignment. What will happen if the order of columns in the query selection has been modified by your colleague? Then, you also require to modify the underlying code that does the extraction. It is an just an overkill to use these methods.

这样做的缺点是数据对齐。 如果您的同事修改了查询选择中的列顺序,该怎么办? 然后,您还需要修改执行提取的基础代码。 使用这些方法只是一个过大的杀伤力。

The problem above is the “reason” why most developers are writing it using the indexer reader["PropertyName"] so the alignment will not be affected. The problem to this is the requirement of conversion. That method returns an object and you are required to cast it to the correct CLR Type, though underneath, the data type is already correct after your extraction. This conversion is an additional logic in your application that could result to a more memory-usage and slower execution.

上面的问题是“原因”,为什么大多数开发人员都使用索引器reader["PropertyName"]编写它,因此对齐不会受到影响。 问题在于转换的要求。 该方法返回一个对象,您需要将其强制转换为正确的CLR类型,尽管在提取之后,数据类型在下面已经是正确的。 这种转换是应用程序中的附加逻辑,可能导致更多的内存使用和较慢的执行。

In the case of ORM, it uses the Get<Type>() methods in all case of extraction and conversion. Since the ORM knows how to project the class properties and table columns, it also knows the position of the mapping. This projection and the call to the correct Get<Type>() method is then a part of the compilation, resulting to a much more robust compiled-function.

对于ORM,在所有提取和转换情况下,它都使用Get<Type>()方法。 由于ORM知道如何投影类属性和表列,因此它也知道映射的位置。 然后,此投影和对正确的Get<Type>()方法的调用是编译的一部分,从而产生了更强大的编译函数。

5.缓存可重用性 (5. Cache Re-usability)

To make the execution more faster and efficient, cache the compiled function and re-use it for future executions.

为了使执行更快,更高效,请缓存已编译的函数,并将其重新用于以后的执行。

Lastly, compilation takes time, but why compile all the time if we can just cache it for future use? This is exactly what ORM is doing. Behind the scene, without you knowing it, ORM does place the already-generated compiled functions into the memory of the computer where the application runs. It then uses the same cached function when the same method is invoked again in the future.

最后,编译需要时间,但是如果我们只能将其缓存以备将来使用,为什么还要一直编译呢? 这正是ORM所做的。 在幕后,在您不知道的情况下,ORM确实将已经生成的编译函数放入了运行该应用程序的计算机的内存中。 然后,当将来再次调用相同的方法时,它将使用相同的缓存函数。

Not just that, ORM also does the kind of caching below.

不仅如此,ORM还可以进行下面的缓存。

  • Type/Object Caching — where all object reflections are stored.

    类型/对象缓存 -存储所有对象反射的位置。

  • Schema Caching — where all retrieved schema from DB are stored.

    模式缓存 -存储从数据库中检索到的所有模式的位置。

  • Mapping Caching — where all the pre-defined project of the properties/columns are stored.

    映射缓存 -存储属性/列的所有预定义项目的位置。

  • Property/Column Caching — where all the extracted type properties are stored.

    属性/列缓存 -存储所有提取的类型属性的位置。

  • SQL Text Caching — where all the already-generated operation command-texts are stored.

    SQL文本缓存 -存储所有已经生成的操作命令文本。

  • Primary/Identity Caching — where all the object primary/identity columns are stored.

    Primary / Identity Caching —存储所有对象的主要/标识列。

It takes a little time to compile the functions as it requires memory allocation when instantiating the necessary objects (i.e.: Lists, Dictionary, etc), and also determining the execution paths. This is also the reason why most “first” execution in ORM is slow. However, once everything is compiled and cache, further execution would be extremely-fast.

在实例化必要的对象(例如:列表,字典等)以及确定执行路径时,由于需要分配内存,因此需要花费一些时间来编译函数。 这也是ORM中大多数“首次”执行缓慢的原因。 但是,一旦所有内容都已编译并缓存,则进一步执行将非常快。

I hope this article gives you enough information about an ORM and will help you decide to choose an ORM on your Software Development.

我希望本文能为您提供有关ORM的足够信息,并有助于您决定在软件开发中选择ORM。

~ Thank you for reading this article!~

〜感谢您阅读本文!〜

If you are interested in learning RepoDb, please visit any of the links below.

如果您有兴趣学习RepoDb ,请访问下面的任何链接。

Or, you can visit the official blog of our great Scott Hanselman.

或者,您可以访问我们伟大的Scott Hanselman的官方博客。

Lastly, the official documentation can be found at RepoDb.NET.

最后,可以在RepoDb.NET上找到官方文档。

翻译自: https://medium.com/@mikependon/the-essentials-of-orm-framework-in-your-software-development-837131efd91b

orm框架开发c#

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值