存储库模式分步说明 [英] Repository Pattern Step by Step Explanation

查看:18
本文介绍了存储库模式分步说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释.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.

推荐答案

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

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.

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

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!

这篇关于存储库模式分步说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆