Asp.net Mvc: Creating Model Classes with LINQ to SQL - asp.net-mvc

I am trying to learn Asp.net Mvc so I am trying out
this Tutorial.
They talk about the Repository Pattern and how it is easy to change to another data access technology instead of just calling Linq to Sql directly.
Using LINQ to SQL within a controller class makes it difficult to switch data access technologies in the future. For example, you might decide to switch from using Microsoft LINQ to SQL to using the Microsoft Entity Framework as your data access technology. In that case, you would need to rewrite every controller that accesses the database within your application.
Note: I never really understood how an interface worked before reading this tutorial and it's still not 100% clear. I see it now as some sort of 'template' for a class.
After successfully using Linq to Sql I thought it would be nice to try out Ado.net Entity Framework since I've been reading a lot about this. They said using the Repository Pattern would make it easy to switch so I thought I would test that.
My question is: what should I do to change to Ado.net EF?
This is what I think I should do.
Add the Movie.edmx file and configure it(add my movie table).
Write a new class based on the IMovieRepository and maybe call it MovieEFRepository.
Change the parameter in the controller constructor to MovieEFRepository. This is the first thing I find strange because in the tutorial they say that not using the repository will force you to change all the controllers if you change to an other datasource. Don't I need to change every controller anyway since I am specifying the MovieRepository class?
The last adjustment I think I need to do is to change the View. Because it's using the Product class which was created by the Linq to Sql designer. I am not sure how I am going to do this. I guess I should have used some object that wasn't dependent on the dbml file?
Forgive me if I have a slightly simplistic view of Asp.net Mvc. I am webdesigner with a lot of interest for Asp.net webdevelopment.

So after a few days of reading and a lot of googling I got it to work. First I tried to find out what IoC (Inversion of Control) actually meant.
One of the first sites I found was a website with a screencast about Unity. Which is a DI/IoC framework for .Net.
Link: David Hayden screencast on Unity.
Looking at it now this is actually a very good screencast and example on how easy it is to use Unity and IoC/DI. At the time I didn't understand it completely so I went on and kept googling.
One website I kept running into was the one from Martin Fowler.
Link: Martin Fowler - IoC Container and the DI pattern
For me, a person that is a coding novice this website is a little to abstract. Also this might sound weird but the font, line-height and typography on that website was really awful which made it even harder to read.
The next website I read was about Windsor Castle since Alfredo Fernández said it was easy to use.
Link: Castle Project- Windsor Container
The documentation wasn't to bad but I had some problems converting their "getting started" basic example to my Asp.net Mvc application. Also part 2 and 3 were missing from their getting started.
After this I started looking for the different frameworks to see if i could find a really basic example. If I just looked at the first screencast again I would have fixed it a lot sooner but somehow I lost track of it.
Link: Scott Hanselman: List of .NET DI Containers(IOC): very good blog post with most of the .NET IOC solutions.
Link: Phil Haack: TTD and DI using Structure Map: Using the xml configuration file was to complicated for me and i couldn't get it to work.
Link:
Andre Loker: ASPNET-MVC-with-Windsor-programmatic-controller-registration: Didn't try this example. Looking at it now I might have been able to get it to work.
Link: MvcContrib: This adds functionality to Asp.net Mvc. It also has 3 or 4 IOC ControllerFactories build in. I couldn't get it to work I also didn't find a lot of documentation about this.
I had a lot of problems with xml configuration files and I couldn't seem to get them to work. I tried Windsor, Structure Map and Spring.net but I always got stuck with the xml files.
So I decided to go to the Asp.net Mvc site because that's where I started learning about Asp.net Mvc. I found the first screencasts and MIX09 presentations very clear and I understood most of what people were talking about. I got stuck at the second screencast by Rob Conery when building the Storefront application. Because I knew a little more about repository and IOC/DI now I thought it would a be a good idea to start watching Rob Conery's screencasts again. In one of the screencasts he talks about uploading all the samples to codeplex.
Link: Codeplex: Mvc sample apps
I went to codeplex and found out you can browse through the source files without downloading them. I tried to find out how Rob Conery handles IOC/DI with his repositories. So I was glad to see he was using Structure Map but instead of using a xml configuration file he was using a bootstrapper class that registers all the interfaces to their concrete class.
After trying this with my webapplication I finaly was able to get Structure Map to work in my application (Hooray).
He also showed me how to fix the dependency on my Product class that comes from Linq to Sql. He creates an extra object that then gets called by "select new product { }" in the Linq queries.
Wow, this answer is a little longer than I planned but I hope this helps other people like me who are very novice in coding and Asp.net Mvc.

You might have your repository decoupled because of injection, not if you followed just the examples because of
public MoviesController() : this(new **MovieRepository**())
I recomend you to read about IOC, is easy and very interesting, you can use and ioc container like castle windsor.
With that, your contoller will have only one constructor, the one with the interface, and not will need to be changed.
With your entities you can do the same that with the controllers, create an interface for each entity and use the ioc pattern too, with tha you will only have to change your configuration file for your ioc container.
If you don't do these things, your right, you will need to change all you said.
I hope that help! sorry about my english!

Related

MVC 4 / Razor in layman's terms

I'm sorry if this is a stupid or obvious question, but I've spent the better part of a week researching, and I really can't find any resources that explain what MVC 4 and Razor are, and what they are intended to do in web development. I'm not necessarily asking for a really detailed description, even a link to a website or the name of a book that doesn't explain MVC 4 by referencing other technologies that I have also never used. I've looked through articles, articles and tutorials on everything from MSDN to graduate papers and I just don't get it.
I know what MVC the design pattern is, but one of the main things I can't get a straight answer to is what the difference is between MVC the pattern and MVC 4 the framework. As a web developer, will I ever have to change or make use of the frameworks, or is it something that is supposed to "stay out of your way" (to quote another SO post.) Is it something that gets generated by VS and I will never have to touch?
Again, I'm sorry if this is obvious, maybe I'm trying to make this more complicated than it actually is. All I have been looking for is a straight forward answer with concrete examples that don't contradict or complicate it any further.
Please...I'm at my wits end here. My last question was apparently too vague and got voted down and closed, so I tried to be more specific, but part of my problem is what are the right questions to ask.If there is anything that can say to clarify,please tell me.
I certainly don't want to discourage you any more than you appear to be at the moment, but in my opinion, if you can't make head or tail of the huge amount of material that already exists on MVC, then perhaps you are just not ready for it yet. That's OK - in fact Microsoft recognise that MVC is complicated, which is why they introduced the ASP.NET Web Pages framework (which is what gave birth to Razor syntax).
My advice would be to follow the link and download WebMatrix. Then follow some of the Web Pages tutorials. That way you can get your head around Razor without worrying too much about MVC for the time being.
Incidentally, ASP.NET MVC is a web development framework that enables you to build web applications based on the MVC pattern. You need to understand how MVC works in order to make use of the framework. You need to understand what Models are, what Views are and the role that Controllers play in the whole thing.
The framework itself is not an example of MVC.
Razor is a templating syntax that allows you to intermix C# (or VB) with HTML to output dynamic content in a View in MVC or a page in the Web Pages framework.
I know it may seem confusing, but it seems to me that you are over complicating things.
The simple matter is that MVC is a design pattern. That is, it's an abstract thing.. a philosophy of sorts. It's not a concrete thing. A design pattern simply gives you a description of how the pattern is supposed to work, and while it may give you a sample implementation, in general it leaves that implementation up to you.
ASP.NET MVC (whichever version) is a specific application framework that uses the MVC pattern as its basis. In other words, it's a concrete implementation of the MVC design pattern.
In fact, the ASP.NET MVC implementation isn't even a "true" implementation of the MVC design pattern, as certain compromises are necessary to make it work in a web based model. So it's really more "MVC design pattern inspired".
You're overthinking things. Just accept that ASP.NET MVC is a framework library that implements and MVC design pattern.
As for Razor, it's merely a templating library. That is, it allows you to define a page layout as text, and insert values at specific places (place-holders). It also allows code to be executed during the process of rendering a template, although this is discouraged in MVC except for very simple cases.
Razor is also used in ASP.NET WebPages technology, in those cases it tends to be more like PHP or classic asp in that all code exists in code blocks within the template itself. Both ASP.NET and WebPages use the Razor templating engine (also called a View Engine) but they use them in different ways.

Breeze with a Unit Of Work/Repository pattern

I was just wondering how I should go about implementing breeze's EFContextProvider in a separate data layer project. Also, since that project is a class library and not an MVC 4 application, how should I include this into my project? I don't really need the whole bag of tricks that is in the Breeze NuGet package, just EFContextProvider stuff. I want to implement a Unit of work pattern using the EFContextProvider DbContext wrapper, like John Papa has done in his wonderful pluralsight course. Has anyone done this yet? any tips?
Thanks
We've got a more sophisticated sample coming called "TempHire" that has a full blown UoW with Repos and separate model projects.
Breeze.NET components (the .NET server-side helpers for a Breeze app ... if you're going with .NET) are all in a single .DLL They have no dependence on MVC at all ... zip. There is Web API stuff in there. Maybe that's what concerns you. Well ... remember that this is open source on GitHub. You are not constrained to the Breeze .DLL. Build your own out of the parts you want.
In my view, the UoW is a short hop from Repository. If you understand what a bounded context is and can translate that to a DbContext implementation, I figure you shouldn't need much help making the transition yourself. There's no magic to it.
For everyone I highly recommend Scott Allen's videos on Repository and UOW in the Pluralsight Design Patterns course ... perhaps the clearest, jargon-free exposition of these patterns I've ever seen.
Here is a post from the Breeze folks about how to use a UoW and Repo on the server with Breeze
http://www.breezejs.com/spa-template#server

Petapoco MVC Example

Where can I find an example of a MVC large solution that has been made with Petapoco?
I'm currently using PetaPoco with MVC. However, I'm using Managed Extensibility Framework (Mef) and the repository pattern. I only state this since your solution shouldn't care if it's PetaPoco, Entity Framework or any other Data Access Layer (DAL). Your end result should be not to tightly couple any framework to your solution - when applicable of course. You'll most likely see the repository pattern in the examples listed by #BalusC - which are great examples by the way.
So, not really on topic with your question, but I think its important to start with the right question - which should be "How should I integrate PetaPoco with a large MVC solution" Think about using PetoPoco with some sort of Dependency Injection like NinJect or using Mef to "import" your repositories.
I hope this helps.

Is there an official ASP.NET MVC reference/example app?

I'm struggling to find a good reference application for ASP.NET MVC. By "reference", I specifically mean an application that flexes all of the framework's features in the Microsoft-sanctioned manner, such as:
Master pages
Partial views
Strongly-typed models
Authentication
Custom routes
etc...
The open source examples that are out there (CodeCampServer, SutekiShop) either add significantly to the base framework or don't use all of the baked-in features.
Have you seen Rob Connery's MVC Storefront Webcast Series?
http://www.asp.net/learn/mvc-videos/#MVCStorefrontStarterKit
Source Code:
http://www.codeplex.com/mvcsamples/
I asked more or less the same question here: What are some projects which are examples of best practices for ASP.NET MVC?
As for official, the closest would be Rob Connery's which was mentioned.
This isn't official but you could check out Kigg:
http://www.codeplex.com/Kigg
It's a sizable Asp.net MVC Digg-clone with some decent code in it. Used on dotnetshoutout.com
I would consider the Nerd Dinner MVC reference app: http://nerddinner.codeplex.com/ for people just starting
While this might be a little late to the show, I believe that the ASP.net team would like people to start using the MVC Music Store as the official mvc reference example. The Music Store application is using the Razor view engine with Entity Framework's code first approach (also demonstrates database first) along with examples of dependency injection, test driven development, jQuery integration and getting and using NuGet packages.
A second reference example seems to be more on the cutting edge of things and is provided by the Patterns and Practices people. This is called the Silk Project and takes advantage of the latest web standards like HTML5, CSS3 and ECMAScript 5 along with modern web technologies such as jQuery, Internet Explorer 9, and ASP.NET MVC3.
These together would probably show you the newest in ASP.net MVC development along with some pretty neat ideas and examples.

How should I structure a simple ASP.NET MVC app?

I've been reading a few things about ASP.NET MVC, SOLID and so on, and I am trying to figure out a simple "recipe" for small-to-medium ASP.NET MVC apps that would put these concepts together; the issue that I am most concerned with is ending up with controllers that are too complex and being like code-behind files in webforms, with all type of business logic into them.
I am considering the following architecture, for a small data-driven app:
Controllers: only handle requests, call an appropriate service and return the action result to the View;
Models: POCO, handle all the business logic, authorization etc. Depends on repositories, totally ignorant of persistence infrastructure.
Repositories: implement IRepository<T>, use dependency injection and is where my db code will reside; only receives and returns POCO.
I am considering having services between the controllers and the models, but if they will just pass forward method calls I am not sure how useful it would be.
Finally there should have unit tests covering the model code, and unit+integration tests covering the repository code (following the "red-green" practice, if possible)
Thoughts?
Ian Cooper had a good post on exactly this recently:
The Fat Controller
Simple recipe: (view)Presentation Layer using ASP.NET, (controller)Code Behinds or AJAX Services Layer, (model)Application Services layer, Business Model layer, and Persistance/Data Access layer.
Of course you can slice and dice numerous ways to deal with complexities in order to build a clearly readable and understandable application.
For a recent discourse on the subject, which I have found to be very good, check out this newly published book: Microsoft .NET: Architecting Applications for the Enterprise.
These walkthroughs are quite helpful:
MVC Framework and Application Structure
Walkthrough: Creating a Basic MVC Project with Unit Tests in Visual Studio
Also see: aspnet-mvc-structuring-controllers
Rob Conery has the best answer IMO.
Check out his MVC Storefront Application, which comes with complete source code and video tutorials.

Resources