I am currently in the beginning of designing an MVC application.
While running some tests through a prototype I came across an issue with the way some data is being handled.
Here's a simple DB diagram
When working on my prototype, I noticed that when the Entity Framework builds all of the required models from SQL it creates an ICollection relationship from the Employee_Table to the Job_Position_Link_Table. I cannot access attributes directly in the Job_Position_Link_Table if the view is strongly typed to the Employee_Table. Also I cannot get to the Job_Position_Title_Table as well. I looked into creating a ViewModel for this issue, but cannot find a good tutorial on how to create the ViewModel when you are working with an ICollection. Most tutorials are from a code first approach, and I am dealing with an inherited database.
The other solution I was thinking of was creating all of my Views in SQL and then passing them into MVC.
I am still new to MVC, and was just wondering what the best practice in this scenario would be?
You should never bind your views to EF entities. Instead, create view model classes with required properties and convert the EF entities into these VMs (you can do that manually or with the help of auto mapper). Then, your views can be bound to your view models.
Its the job of controller to build the view model and send it to view engine for rendering. Thus, view must expect a view model ready for presentation.
Related
I'm having a royal time delegating rote view generation to runtime and a rich view model. This move away from the dynamic compilation of richer Razor views has the drawback of requiring frequent rebuilds to play with small view model changes though.
What are my options for a more dynamic viewmodel/metadata meeting than the good old POCO data annotation attributes on my view model? The most obvious is a complete custom metadata provider that sources model metadata from a file or database, but I'm asking this question to get some ideas for other approaches. Maybe dynamically compiled POCO's, or a scripting engine?
The entire purpose of a View Model is to create a strongly typed model. What you want to do cannot be done with strong typing, so using a View Model is pointless.
Either put up with having to recompile, or use ViewData for your data.
I'm a little unsure how it is you plan to make view model changes without recompiling anyways.. your controller needs to know about the ViewModel and if it changes, it will throw runtime exceptions.
Quick question about database views. Am I right in assuming that I can create a database of view of various tables and connect them how I want etc and then when I do queries, add, edit delete etc then MVC will figure it all out for me without needing to do any complex SQL in the controller or repository?
Odd question but just wanted to make sure my assumption was valid. Cheers
Unfortunately, MVC will not figure it all out for you, you'll still need to write the SQL code (or use an ORM framework) to communicate with the database.
What MVC gives you with it's architecture is a clear separation of responsibilities:
Views are responsible for displaying data and should be as simple as possible (i.e. little to no logic in them)
Model(s) contain the business logic and rules
Controllers are responsible for passing data between the Model and the Views.
What you are looking for is Scaffolding. In .net MVC I can't think of any tools which do this for you directly against the database. They all require either as Russ said an ORM i.e. Linq To SQL or Entity Framework (EF).
http://msdn.microsoft.com/en-us/library/cc488540.aspx
The closest you could get would be to use Database First model generation and then put the necessary MVC templates/views/code on top.
A database view is read-only so you will not be able to perform write operations on the view. You can however create a model from a view and display your data as defined from the view. If you are using an ORM solution such as ADO.NET Entities you can instantiate an object and add the child objects to it and be able to save the final result in a single transaction as well.
I'm building a concept application with MVC 3 in an attempt to learn its ways. I've previously done some very heavy-duty applications in WebForms, using an n-tier approach, usually consisting of domain objects with repositories for storage and services to manipulate them before storage.
I'm trying to reconcile how I used to do things with the "right" way to do them in MVC, if there is any one such way. The thing I'm getting hung up over right now is when to use ViewModels versus when to use my domain objects that are in a whole other project. Validation is done with ViewModels, but as I write more customized, business-logic validation, it seems like it's too much responsibility on a lowly ViewModel that was just there to help me move data around before storing it officially in the database through the repository layer.
I'm also getting tired of mapping ViewModel data to the "official" domain object that the repository stores and retrieves, but I feel like I shouldn't tarnish my domain objects with the MVC attributes for validation, either.
Do you have any advice for where to draw the line between domain objects and mere ViewModels? Or am I complicating things, and my ViewModels should actually be the "official" models that the repository stores?
Do you have any advice for where to draw the line between domain objects and mere ViewModels?
Personally I always use View Models. All UI validation logic is done on the view models (required fields, ...) and business logic on the domain models (username already exists, ...). I also use AutoMapper in order to not get tired of mapping between the domain models and the view models that are passed to the view.
I generally default to using View Models, though for read-only views, I have been known to use the domain model (no reason to go through the overhead of mapping if I am only going to read data out of it).
If you do decide to use domain models, I would never let MVC bind directly to them, because if someone knows your domain well enough, they can post values that bind to properties you do not want the user to be able to edit. You can define white and black list of properties of what model binder can and cannot bind to, but utilizing that is something else you'll have to maintain and something that can easily be forgotten about.
I think the best approach is to use view models ALWAYS. These are about presentation concerns and should be where basic input validation is handled. Domain objects are not appropriate for this.
I use specific view models per view and only include the information that is needed in the view - keeping view models totally view-centric makes for nice clean views.
You can use Automapper to help remove the drudgery of moving between view and domain models.
Can I recommend ASP.NET MVC 2 in Action as a great book for strong ASP.NET MVC patterns. This covers using Automapper in detail.
Domain models and ViewModels will look very much like each other. However, ViewModels usually contain view logic attributes and properties. Also sometimes data type can be different, for example you might need to define a DateTime property as string just get the validation working without raising any errors.
I am using AutoMapper to convert from Model to ViewModels/vice versa.
ViewModel are good but don't forget Validation attributes are not only limited to MVC projects, you can use them in any .net project. Because of this it can make sense to apply the validation attributes to your domain objects, preferably by using a partial class and/or a Validator class http://weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3.aspx
My approach is that a ViewModel model should be associated to a single view (or least a set of related views), and is usually a sub-set of your domain model. I see a ViewModel as responsible for UI validation, where as your domain object is responsible for business rule validation.
As for mapping between the two, highly recommend using Automapper which can automatically map properties based on conventions, it's a huge time saver.
I'm new to MVC and even though there is a lot (and I do mean a lot) of information out there that is very useful - it's proofing very difficult to get a clear understanding on how to achieve my exact requirements with MVC 2.0.
I would like to set up a solution as follows:
Provide a web UI using an MVC 2.0 project.
Use Linq to SQL classes project for data persistence.
I have a two separate code modules that will need to access the above Linq to SQL model - so I won't be able to include my Linq to SQL model directly in the MVC project itself.
Also I have a Business Logic layer in front of my Linq to SQL project.
My questions are:
How do I set up the Model part of my MVC application to point to my Linq to SQL project via my BLL?
How do I perform web app validation? Can I use MVC 2.0 Model Validation? If not what are the alternatives?
Finally (and slightly aside) - What is the ViewModel and how does this differ from the Model?
So many questions. But this is an exciting new technology and data access issues aside, everything else I've got to grips with very quickly and I think MVC 2.0 is fantastic.
Thanks for any pointers you can provide.
How do I set up the Model part of my
MVC application to point to my Linq to
SQL project via my BLL?
Typically you'd use a repository pattern for this. Your controller has a reference to your repository - the repository returns your domain objects from your database. The MVC app has no knowledge LINQ to SQL exists.
How do I perform web app validation?
Can I use MVC 2.0 Model Validation? If
not what are the alternatives?
Put view models in your MVC project. These view models may closely align with your domain models but their concern is to be the presentation model. Put your data annotations for validation on these view models - the MVC framework will automatically ensure validation occurs on these view models decorated with data annotations. It's pluggable so you could use alternatives - but with MVC 2, it's baked in fairly well and this includes client side validation.
Finally (and slightly aside) - What is
the ViewModel and how does this differ
from the Model?
I partially answered this one above. the shape of your domain models may not be the shape you need to display your views - view models are great to bridge this gap. Additionally, even if the shape does match exactly - view models are still a good idea so that you can put UI validation code there and other presentation meta-data on them (since you do not want anything related to presentation logic on your domain model).
Here's link for view model patterns.
Hope this helps.
You can add a reference to the objects exposed from your BLL assembly and use them as your Models.
When you want to add validation to classes that are generated use buddy classes.
A ViewModel is a custom-shaped aggregate of Model data. There is exactly one per View, as the ViewModel's purpose is to surface exactly the data needed by a particular View in a convenient and concise way.
An example might be a View that contains both Order and OrderDetail information. A ViewModel can hold internal references to the repositories and business objects for each type. Properties of the ViewModel merge together the data from these objects.
ViewModels will be useful in your case also because you want your Models to be in a separate assembly. You can apply the DataAnnotations to ViewModel properties for validation. You would make the "raw" business object models internal properties of your ViewModels, and expose public methods to retrieve and persist data.
I'm familiar with the various bits of functionality of the MVC plugin to create things. For example you can create a controller, write an Action method on it, then use the "create view" function in the context menu to create a view for it.
The question is, which is it recommended to do first?
I'm thinking I might start myself a methodology like this:
Plan out what the UI etc will look like and how it will work.
Write unit tests for the controller actions I think I might need.
Create Controller (maybe with default CRUD actions if it's to be that kind of controller).
Create ViewModel class for each controller action.
Create a strongly-typed view for each ViewModel.
Start building the view, working back through the ViewModel to the Controller as the View is built up.
What do you think of this approach, and what do you do?
Sounds like you're on the right track. Controllers are the most easily tested component of the three. Going controller-first will make it easier to follow Test-Driven Development practices.
I've not been perfectly happy with the default view templates, but every MVC guru will point you to T4 templates, which let you roll your own. They, like the out-of-the-box view templates, will be more effective with existing view models and controllers.
I'd be tempted to define the ViewModel first, the VM(s) can consist of all or a subset of the entities required for the various Views. How you segregate your VMs would depend on your app and how you are breaking up logical units within that.
Once I had the VM(s) in a basic form I would move to Model necessary for my chosen data store (unless I had an existing data store in which case I'd have started with the Model). Then onto the controllers. You can then apply TDD with a mocked data source to verify that the VM objects returned by the controller actions match expectations. Lastly, I'd generate basic strongly typed Views (based on the ViewModel objects) for each controller action that actually resulted in UI.
Then it's play time with Jquery and CSS to make it look presentable.