问题描述
可有人请向我解释一步给人一种很简单的例子或演示.NET中的存储库模式,一步。
Can someone please explain to me the Repository Pattern in .NET, step by step giving a very simple example or demo.
我知道这是一个非常普遍的问题,但到目前为止,我还没有找到一个满意的答案。
I know this is a very common question but so far I haven't found a satisfactory answer.
推荐答案
作为总结,我会形容库模式的广泛影响。它可以让你所有的code使用的对象,而无需知道对象是如何坚持。所有的持久性的知识,包括从表到对象的映射,安全地包含在库中。
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.
很多时候,你会发现散落在codeBase的SQL查询,当你来到一个列添加到表,你必须寻找code文件,试图找到一个表的用法。变化的影响是深远的。
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.
使用存储库模式,你只需要改变一个对象,一个存储库。的影响是非常小的。
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
有其他的好处太多,例如,如果你使用MySQL,想要切换到SQL Server - 但在实践中我从来没有真正看到这个
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!
这篇关于分步说明Repository模式步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!