问题
In Orchard CMS using IRepository<>
is quite common.
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<>
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
from r in Repository where r.ID == 1234 select r.Name
回答1:
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.
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.
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.
Here when you run your unit test, It won't hit the db, instead it will return dummyCustomer
回答2:
I agree with Bertrand that you should always use IContentManager for db stuff, but the only one usage I can think of for using IRepository<> instead of IContentManager is for records based items only, i.e. records that don't have parts, in such case the only way to do db stuff on them is via IRepository
回答3:
In the context of Orchard, you should in general never use either. Repositories are an implementation detail that should almost never be used (see https://weblogs.asp.net/bleroy/just-forget-that-repository-t-exists-please). Linq to SQL is abandoned ORM technology that has never been part of Orchard. Orchard uses nHibernate, and your best bet is to use the nHibernate Session directly for low-level database access, and to use the Content Manager API for higher-level querying.
来源:https://stackoverflow.com/questions/33633474/orchard-irepository-vs-linq-to-sql