Search code examples
c#linq-to-sqlorchardcmsirepository

Orchard IRepository vs. Linq to SQL


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

Solution

  • 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