C# 存储库模式分步说明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11985736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:58:22  来源:igfitidea点击:

Repository Pattern Step by Step Explanation

c#asp.netdesign-patternsrepository

提问by Sa Patil

Can someone please explain to me the Repository Pattern in .NET, step by step giving a very simple example or demo.

有人可以向我解释 .NET 中的存储库模式,逐步给出一个非常简单的示例或演示。

I know this is a very common question but so far I haven't found a satisfactory answer.

我知道这是一个很常见的问题,但到目前为止我还没有找到满意的答案。

回答by twoflower

This is a nice example: The Repository Pattern Example in C#

这是一个很好的示例:C# 中的存储库模式示例

Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:

基本上,存储库隐藏了数据是如何从/向数据库获取/持久化的详细信息。在封面下:

  • for reading, it creates the query satisfying the supplied criteria and returns the result set
  • for writing, it issues the commands necessary to make the underlying persistence engine (e.g. an SQL database) save the data
  • 对于读取,它创建满足提供条件的查询并返回结果集
  • 对于写入,它发出使底层持久性引擎(例如 SQL 数据库)保存数据所需的命令

回答by Fenton

As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.

作为总结,我将描述存储库模式的更广泛影响。它允许您的所有代码使用对象,而不必知道对象是如何持久化的。持久性的所有知识,包括从表到对象的映射,都安全地包含在存储库中。

Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.

很多时候,您会发现 SQL 查询分散在代码库中,当您向表中添加列时,您必须搜索代码文件以尝试查找表的用法。变革的影响是深远的。

With the repository pattern, you would only need to change one object and one repository. The impact is very small.

使用存储库模式,您只需要更改一个对象和一个存储库。影响非常小。

Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:

也许思考一下为什么要使用存储库模式会有所帮助。以下是一些原因:

  • You have a single place to make changes to your data access

  • You have a single place responsible for a set of tables (usually)

  • It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests

  • 您可以在一个地方更改您的数据访问

  • 你有一个地方负责一组表(通常)

  • 用虚假的实现替换存储库进行测试很容易 - 所以你不需要有一个可用于单元测试的数据库

There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!

还有其他好处,例如,如果您使用 MySQL 并想切换到 SQL Server - 但我在实践中从未真正见过这种情况!