Orchard IRepository与Linq to SQL [英] Orchard IRepository vs. Linq to SQL

查看:143
本文介绍了Orchard IRepository与Linq to SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在果园CMS中,使用IRepository<>很常见.

In Orchard CMS using IRepository<> is quite common.

所以我问自己,使用IRepository<>及其Fetch()方法而不是简单地使用Linq to SQL查询数据有什么好处?

So i ask myself, what is the advantage of using IRepository<> and its Fetch() method instead of simply using Linq to SQL to query data?

IRepository<>

IRepository<>

Repository.Fetch(r => r.ID == 1234).Select(r => r.Name)

这里的缺点是我必须将存储库注入构造函数中.

The disadvantage here is that i have to inject the repository in the constructor.

Linq to SQL

Linq to SQL

from r in Repository where r.ID == 1234 select r.Name

推荐答案

通常,存储库是数据访问代码之上的抽象.您的IRepository接口可能有多种实现,一种使用LINQ to SQL作为数据访问技术,另一种使用Raw ADO.NET或另一种使用XML文件作为数据存储.通过此存储库抽象,访问数据(例如:repository.GetCustomer(someId))的前端代码保持不变.我们可以根据需要简单地清除限制.

Generally Repositories are an abstraction on top of your data access code. You may have multiple implementations of your IRepository interface,One which uses LINQ to SQL as the data access technology and another one using Raw ADO.NET or another one using XML files as data storage. With this repository abstraction, your front end code where you access data ( ex : repository.GetCustomer(someId) ) stays same. We can simply swtich the implemntation as needed.

具有此抽象允许您为代码编写单元测试.您只需要创建一个IRepository的模拟实现.您可以使用Moq之类的模拟库来实现此目的.

Having this abstraction allows you to write unit tests for your code. You just need to create a mock implementation of your IRepository. You may use mocking libraries like Moq to achieve this.

使用Moq进行单元测试代码的快速示例

Quick example of your unit test code using Moq

var repo= new Mock<IRepository>();
var dummyCustomer = new Customer { Name ="Test"}
repo.Setup(s=>s.GetCustomer(It.IsAny<int>).Returns();

var customerMgr = new CustomerManager(repo.Object);
var actualResult = customerMgr.GetCustomer(345);

//Assert something now.

在这里运行单元测试时,它不会命中数据库,而是返回dummyCustomer

Here when you run your unit test, It won't hit the db, instead it will return dummyCustomer

这篇关于Orchard IRepository与Linq to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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