knocked up a clockwork orange men in black movie download changeling napoleon dynamite movie download desperado psycho superman returns movie download artificial intelligence: ai the lord of the rings: the return of the king movie download robot chicken: star wars movie download aladdin movie download city of god x-men dog days of summer carlito's way signs movie movie download drag me to hell movie download movie download the notebook blood diamond movie download platoon movie download serenity gone in sixty seconds movie download movie download ice age the butterfly effect stand by me movie download there will be blood movie download movie download harry potter and the sorcerer's stone movie download christmas in south park anchorman: the legend of ron burgundy movie download movie download hulk mystic river the 10th kingdom movie download the talented mr. ripley movie download the last samurai the hangover star wars: episode vi - return of the jedi movie download movie download trainspotting 2001: a space odyssey the international movie download l.a. confidential movie download forrest gump movie download kill bill: vol. 1 movie download movie download control batman begins movie download the diving bell and the butterfly movie download o brother where art thou? movie download movie download watchmen movie download ferris bueller's day off the godfather: part ii as good as it gets the shining movie download the great escape blade runner (final cut) citizen kane the apartment movie download 12 angry men sleuth movie download the island rocky atonement movie download the fugitive movie download spider-man 2 movie download ocean's eleven movie download the insider moulin rouge! movie download the african queen movie download obsessed movie download kill bill: vol. 2 movie download gone baby gone movie download new in town aka chilled in miami movie download the da vinci code movie download the incredibles movie download the telling the elite squad iron man movie download stardust reservoir dogs movie download edward scissorhands borat big fish movie download full metal jacket movie download the incredible hulk movie download star wars: episode ii - attack of the clones letters from iwo jima movie download fast & furious 4 300 spartans movie download armageddon movie download spider-man 3 movie download goodfellas movie download notting hill planet of the apes movie download wall-e movie download movie download the matrix reloaded taxi driver sleepy hollow a bug's life unbreakable fahrenheit 9/11 movie download street fighter: the legend of chun-li movie download war of the worlds movie download indiana jones and the last crusade movie download it's a wonderful life the blair witch project movie download transformers the third man the aviator movie download movie download sweeney todd: the demon barber of fleet street movie download lesbian vampire killers underworld movie download romeo + juliet movie download minority report winnie the pooh un-valentine's day movie download twelve monkeys movie download the hunt for gollum movie download tales of the black freighter movie download mean girls movie download the shawshank redemption natural born killers movie download futurama: into the wild green yonder movie download movie download jurassic park confessions of a shopaholic movie download movie download dead like me fired up jeff dunham: arguing with myself paths of glory night at the museum 2: battle of the smithsonian movie download movie download kung fu panda the wild bunch movie download movie download the man from earth if i didn't care movie download movie download mission: impossible ii rambo movie download movie download catch me if you can the 40 year old virgin movie download ace ventura: pet detective jr. movie download i am legend movie download the departed the others movie download movie download american psycho movie download the hurt locker traffic movie he's just not that into you pirates of the caribbean: the curse of the black pearl movie download movie download sicko harry potter and the order of the phoenix movie download movie download the rock movie download die another day movie download groundhog day movie download jaws the elephant man bridget jones's diary crank 2: high voltage the visitor movie download the matrix movie download pulp fiction movie download from dusk till dawn munich dead set movie download boy a closer movie movie download the godfather titanic live free or die hard the prestige movie download back to the future part ii movie download movie download the grudge 3 lost in translation movie download raiders of the lost ark the chronicles of narnia: the lion witch and the wardrobe ratatouille movie download scream movie download garden state finding nemo the pursuit of happyness movie download land of the lost the final inquiry movie download unforgiven movie movie download 007 goldeneye die hard star wars: episode iv - a new hope movie download hancock gangs of new york movie download red is the color of the devil's advocate movie download the matrix revolutions the christmas toy movie download dragonball: evolution vertigo the snowman movie download star trek movie download coraline movie download ben-hur: a tale of the christ van helsing movie download almost famous movie download the leon (professional) movie download rear window movie download singin' in the rain x2 the green mile movie download no country for old men movie download star wars: episode iii - revenge of the sith gandhi movie download the sixth sense movie download movie download the simpsons movie movie download the dark knight the nightmare before christmas movie download the big lebowski back to the future movie download requiem for a dream movie download good will hunting how the grinch stole christmas! movie download movie download chicago 3:10 to yuma movie download in cold blood movie download the phantom of the opera journal of a contract killer movie download green street hooligans 2 movie download movie download superbad the curious case of benjamin button leaving las vegas frost/nixon once upon a time in the west movie download saw dances with wolves movie download movie download indiana jones and the kingdom of the crystal skull movie download scary movie life of brian fargo movie download charlie's angels 21 grams movie download the truman show futurama: bender's big score movie download schindler's list dead poets society ocean's twelve movie download v for vendetta movie download in bruges robin hood: prince of thieves movie download collateral my friends tigger & pooh's friendly tails movie download before the devil knows you're dead movie download cruel intentions movie download the pianist movie download heat movie download shakespeare in love speed movie movie download jackie brown howl's moving castle movie download 17 again movie download making waves five minutes of heaven movie download cool hand luke movie download movie download lawrence of arabia madea goes to jail movie download lucky number slevin movie download last chance harvey movie download vanilla sky movie download lara croft: tomb raider heima the lord of the rings: the two towers movie download little miss sunshine movie download movie download fight club harry potter and the chamber of secrets movie download gran torino penelope movie download silent hill ed wood movie download movie download state of play movie download brokeback mountain movie download i robot movie download independence day life is beautiful movie download movie download saw ii hotel for dogs movie download adventureland lock stock and two smoking barrels movie download sin city movie download die hard 2 movie download monsters inc. movie download eternal sunshine of the spotless mind movie download children of men the silence of the lambs movie download juno interview with the vampire: the vampire chronicles movie download movie download the godfather: part iii beauty and the beast movie download harry potter and the prisoner of azkaban american gangster movie download movie download cloverfield pirates of the caribbean: at world's end movie download the conversation terminator 3: rise of the machines movie download the darjeeling limited star wars: episode i - the phantom menace movie download the mummy movie download bootmen the nines movie download movie download man on wire movie download fear and loathing in las vegas spider-man erin brockovich movie download the chimes at midnight movie download the bourne ultimatum movie download casino royale movie download the untouchables the lord of the rings: the fellowship of the ring movie download star wars: episode v - the empire strikes back movie download echelon conspiracy movie download monsters vs. aliens movie download troy chasing amy movie download movie download the skeptic to kill a mockingbird movie download there's something about mary movie download movie download south park: bigger longer & uncut movie download love actually movie download the bridge on the river kwai rain man movie download shelter movie download 12 rounds movie download austin powers: international man of mystery enchanted movie download movie download bride wars some like it hot movie download movie download american history x movie download gladiator blade runner movie download million dollar baby soldier's girl movie download donnie darko movie download aliens movie download memento movie download casablanca black hawk down braveheart movie download shrek 2 movie download waterworld angels & demons movie download the uninvited movie download the wrestler the princess bride american beauty office space american pie movie download pink panther 2 movie download the bourne identity chop shop the sting glory movie download on the waterfront movie download the last king of scotland movie download slumdog millionaire movie download dogma snatch. being john malkovich finding neverland movie download the fifth element amadeus movie download se7en movie download toy story 2 movie download the english patient movie download star trek: first contact dr. strangelove or: how i learned to stop worrying and love the bomb movie download toy story before sunset gone with the wind movie download one flew over the cuckoo's nest baraka movie download alien pirates of the caribbean: dead man's chest mulholland dr. movie download pearl harbor movie download movie download indiana jones and the temple of doom movie download the passion of the christ harry potter and the goblet of fire movie download x-men origins: wolverine hotel rwanda movie download movie download notorious once upon a time in america movie download movie download terminator 2: judgment day movie download bruce almighty movie download hot fuzz the planets movie download the usual suspects apocalypse now movie download movie download a beautiful mind movie download road to perdition movie download saving private ryan movie download terminator salvation movie download apocalypto movie download home alone shrek movie download movie download underworld: rise of the lycans movie download knowing hannah montana: the movie movie download austin powers: the spy who shagged me race to witch mountain movie download paul blart: mall cop the savages movie download the terminator movie download x-men: the last stand movie download movie download the fast and the furious movie download i'm not there movie download raging bull movie download the ghosts of girlfriends past batman forever movie download

ASP.NET MVC, LINQ and Repository Pattern

from julian on October 13th, 2008

A few days ago I've finally decided to spend some time with Microsoft's new ASP.NET MVC framework. Like all MVC implementations, the ASP.NET MVC framework provides a structured model that enforces a clear separation of concerns within applications, and makes it easier to unit test your code.  It also helps provide more control over the URLs you publish in your applications, and can optionally provide more control over the HTML that is emitted from them. Here is a nice article on the history of MVC pattern.

ASP.NET MVC is in a pre-beta stage, but it is quite stable and there are even production sites running on it. For example, one of my recently favorites stackoverflow.com, a great resource of programming knowledge, is running on ASP.NET MVC. (it is amazing how programmers working on different technologies/stacks can behave together and share the knowledge.)

Update: ASP.NET MVC is now officially in Beta. As usual, to get all the details, check out the latest epic installment on ScottGu’s blog.

The other new technology I wanted to play with is LINQ. A fast description of LINQ from Wikipedia: "LINQ defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes, XML, relational database, and third party data sources. While it allows any data source to be queried, it requires that the data be encapsulated as objects. So, if the data source does not natively store data as objects, the data must be mapped to the object domain. Queries written using the query operators are executed either by the LINQ query processing engine or, via an extension mechanism, handed over to LINQ providers which either implement a separate query processing engine or translate to a different format to be executed on a separate data store (such as on a database server as SQL queries). The results of a query are returned as a collection of in-memory objects that can be enumerated."

And finally, after months working with some old, heavy "spaghetti-code" PHP applications (pre-version 5) I wanted to enforce a design pattern when designing my classes. Specifically, I've decided to implement the Repository Pattern.

The Repository Pattern is a very popular way to abstract a domain model from the underlying data mapping and data access by providing access to domain objects (business objects) via a collection interface. For example, the business objects can form collections under a single repository object such as:

  • Repository.Projects
  • Repository.Customers
  • Repository.Managers, etc.

So, let's go!

Note: all the code listings below are written in C#, but i'm pretty sure the programmers will get the idea :)

First, we need to created the ASP.NET MVC project in Visual Studio. VS automatically is creating the project structure, folders, etc. , plus a test project where we can store the unit tests.

ASP.NET MVC Application

For this sample I have a simple table called "Projects". You can see the structure of the table below:

To create the LINQ classes, we need to add a new "LINQ to SQL classes" item to the Model folder, and then simply drag the "Projects" table to the Object Relational Designer designer. Visual Studio will take care and generate the classes. Additionally, you can drag stored procedures (if any). Later, you can access the stored procedures as methods of the respective LINQ class.

LINQ to SQL class

Ok, we have the MVC project, a table and the LINQ classes already. We need to access the data and pass it the views. We can access the LINQ classes directly from our controllers. For example:

Controllers/HomeController.cs

The Index() action above uses a LINQ to SQL DataContext class to represent the database. The DataContext class was generated by the Visual Studio Object Relational Designer.

A LINQ query is performed against the DataContext to retrieve all of the projects from the Projects database table. The list of projects is assigned to a local variable named allProjects. Finally, the list of projects is passed to the view through view data.

Working directly with LINQ to SQL in a controller class is perfectly fine in terms of MVC. However, it can create problems when you need to build a more complex application. It makes it difficult to switch data access technologies in the future. For example, you might decide to switch from using LINQ to using the Entity Framework, or strongly typed datasets, or whatever you like as your data access technology. In that case, you would need to rewrite every controller that accesses the database within your application. In addition, using LINQ to SQL within a controller class makes it difficult to build unit tests for your application.

The Repository Pattern

In order to build an MVC application that is more adaptable to future change and that can be more easily tested, we can use the Repository pattern. When you use the Repository pattern, you create a separate repository class that contains all of your database access logic.

When we create the repository class, we create an interface that represents all of the methods used by the repository class. Within the controllers, we write our code against the interface instead of the repository. That way, we can implement the repository using different data access technologies in the future.

The interface below is named IProjectRepository and it represents a single method named ListAll().

Models/IProjectRepository.cs

And the repository class below implements the IProjectRepository interface. Notice that it contains a method named ListAll() that corresponds to the method required by the IProjectRepository interface. 

Models/ProjectRepository.cs

Finally, we need to change the HomeController class to use the repository instead of using LINQ to SQL classes directly.

Controllers/HomeController.cs

Notice that the HomeController class has two constructors. The first constructor (the parameterless one) is called when your application is running. This constructor creates an instance of the ProjectRepository class and passes it to the second constructor. The second constructor has a single parameter: an IProjectRepository parameter. This constructor simply assigns the value of the parameter to a class-level field named _repository. This is an implementation of a software design pattern called the Dependency Injection pattern. In particular, Constructor Dependency Injection.

Notice that all of the code in the HomeController class (with the exception of the first constructor) interacts with the IProjectRepository interface instead of the actual ProjectRepository class. The code interacts with an abstract interface instead of a concrete implementation of the interface.

If you want to modify the data access technology used by the application then you can simply implement the IProjectRepository interface with a class that uses the alternative database access technology. For example, you could create an MySqlProjectRepository class or an EntityFrameworkRepository class. Because the controller class is programmed against the interface, you can pass a new implementation of IProjectRepository to the controller class and the class would continue to work.

Furthermore, if you want to test the ProjectController class, then you can pass a fake project repository class to the HomeController. You can implement the IProjectRepository class with a class that does not actually access the database but contains all of the required methods of the IProjectRepository interface. That way, you can unit test the HomeController class without actually accessing a real database.

Nice and simple!

PS. Of course, you can implement as much repository methods as you need. For example (and to show some more LINQ magic) we can implement GetById() method in the ProjectRepository class as follows:

and access it in our controller with something like var myProject = _repository.GetById(5);

Tags: , ,

12 Responses to “ASP.NET MVC, LINQ and Repository Pattern”

  1.  
  2. ASP.NET MVC Archived Buzz, Page 1 Says:


    [...] to Vote[Del.icio.us] East.fi ” Blog Archive ” ASP.NET MVC, LINQ and Repository Pattern (10/16/2008)Thursday, October 16, 2008 from mkelley33SoC or the layerer approach can be achieved via the [...]

     
  3. Andrei Rinea Says:


    There is something that I don’t understand in using LINQ to SQL in Repository pattern :

    Let’s say that I will create an assembly for each of the Repository providers (LINQ to SQL, MySQL, Oracle, WebService, XML files etc. etc.). I will define the IRepository interface in a common assembly (let’s call it ‘Interfaces’) that will be referenced by any Repository provider assembly. But where will the entity classes (’Project’ in your example) be placed? Since they are generated by Visual Studio or by SQL Metal they would live in the LINQ to SQL provider but they are required in the ‘Interfaces’ assembly so I have a circular problem.

    How do I go about this?

     
  4. julian
    julian Says:


    Hello Andrei,
    Interesting question! I don’t have any ready solutions in place. What I can think at the moment, you can add another layer, wrapping the LINK to SQL classes and passing serialized objects to the repository layer (i.e. Fowler’s “Data Transfer Objects”).

    I’ll try to come with something during the weekend.

     
  5. jon Says:


    Great article! Any chance of showing how to create the unit tests with the fake repository?

     
  6. julian
    julian Says:


    Ho jon,
    Basically, you create a FakeRepository class that is a concrete implemetation of your IRepository. You can follow the Rob Conery’s MVC Store Front screencasts for an example on how to test your repositories.

    http://blog.wekeroad.com/mvc-storefront/mvc-storefront-part-1/

    Hope it helps,
    Julian

     
  7. Joao Araujo Says:


    Nice article, thanks!

     
  8. behnam Says:


    hi
    nice articel but There is something about using repository pattern i cant understand. What is difference between repository pattern and n tier architecture? IProjectRepository (in this sampel) .
    isnt the same as bussines login in n tier architecture.
    thanks for your attention

     
  9. DurgaPrasad Says:


    Hello Julian,

    Can you pls publish the complete source code for this application. ?

    Thanks

     
  10. julian
    julian Says:


    @behnam

    I’m thinking of a repository as a part (tier) of my n-tier design. Probably the question should be “what’s the difference between DAL and repository?” and it’s all about interpretation and context. In my projects i’m using LINQ2SQL as DAL generator and the repository as a bridge between DAL and the service layer.

    IMO, the idea behind a repository is that it encapsulates all persistence logic and dependencies on infrastructure from the rest of your application. When your application needs a Project object, it shouldn’t have to know whether it is coming from SQL Server, XML file, or MySQL. Once you have that de-coupling, any changes you make to your persistence story have no effect on the rest of your application.

    @DurgaPrasad

    This is not a complete application but a simple experiment. I’m working on a simple ASP.NET MVC CMS in my spare time at home but i have nothing ready - only a bunch of unit tests, repositories and LINQ partial classes :)

     
  11. bb Says:


    hi
    can you give me a puicture of using repository pattern in enterprize application.
    regard

     
  12. Ratndeep Says:


    I was looking for the info on asp.net mvc with repository pattern and u have given me the all basic understanding.Thanks for this.

     

Leave a Reply


vibram five fingers louise bourgeois julie berman jenna bush christian leblanc tiffany shepherd tedy bruschi darin brooks days of our lives go renew vaco staffing etfc 25.76 .20 vincent irizarry chicago pmi watch true blood episode 11 online akshata murthy usopen watch true blood frenzy deutsche bank golf go renew florida dmv wisconsin no call list darin brooks rich rodriguez min the vermont country store daytime emmy awards 2009 winners kinski fl dmv john utendahl florida department of motor vehicles us open tennis 2009 bj services chicago triathlon mad men season 3 episode 3 college football lines ironman louisville 2009 results fl drivers license renewal prp jeans watch entourage season 6 episode 8 california wildfires mvl ed ruscha mt wilson cam oak glen fire 2 months 2 million episode 3 perez hilton rumor diane watson jeff branson usopen tennis brunswick ga hillsborough county tax collector jenna hager john mayer who says map of california fires separate jam or jelly or preserves susan haskell orderves howdy.tamu.edu true blood s02e11 torrent florida tag renewal detroit free press sports kourtney and khloe take miami episode 3 dj unk heart attack jaycee dugard photos hurricane erika florida dmv labels windows police pro ataris pallidipennis stal pole dancer doll yucaipa fire lindsay breed the munsters nocall.wisconsin.gov brunswick murders mount wilson observatory philip markoff tea party express florida drivers license bill bennett hurricane jimena acton california marvel entertainment rishi sunak disney marvel orchids and growing or planting movies and advertising and sales leah lust anand jon alexander green av virus baker hughes farm progress show accutane freedom communications big brother 11 pandora s box john utendahl tyra banks true blood season 2 episode 12 president clinton and foreign policy frankie beverly