What is the best practice, Entity Framework Models or MVC Models? - asp.net-mvc

When using Entity Framework with Code-First, what is the best practice when calling database data?
This is my first time using Entity Framework with MVC and noticed that it automatically builds Models in my DataLayer. I also have the basic Models within my MVC UI which allow me to manipulate and display the data within my Views. I currently grab the data using my Workflow layer, and then AutoMap the Database Model to my UI Model to display the data.
Is this the best practice? Should I be using the Entity Framework Models instead of my UI Models? Or this even possible to do cleanly?
Any information on the matter would be appreciated.

It's up to you really. If you like to re-use the same EF entities for your view models as well; go ahead. Personally, I prefer not to. This is because you normally end up adding a bunch of properties to the class that have nothing to do with what's stored in the data and yes; I know you can use the NotMapped attribute like this:
[NotMapped]
public string MyExtraProperty { get; set; }
but I prefer not to. Additionally, you end up adding [Display] and other attributes to your properties and before you know it, you've got something decorated with both data specific and UI specific attributes and it can get messy if you're not careful.
So for me; I have the following:
Domain Entity
View Model
Service/Facade/Repository
Controller calls repository to get the domain entity and converts it to a view model for displaying.
I find that to be a cleaner approach, but maybe that's just me.. the most important thing is to just choose one way and stick with it for the sake of consistency and clarity of code, but either method is acceptable.. "whatever floats your boat" as they say...

The POCOs created by EF are supposed to be used as your model. The general idea is that you have EF providing access to your database. You query EF using LINQ and/or extension methods and end up with an object or collection of objects that you display on your UI by binding them in WPF. That is of course if you're using WPF as opposed to the older WinForms. I can tell you from experience that it's a very streamlined process once you become familiar with the technologies. That's how a very basic setup would work.
A more advanced way of going about it is adding architectures like Model-View-ViewModel (MVVM) and possibly the repository pattern into the mix at which point you get better separation of code and presentation at the cost of increased complexity.
I don't know what flavor of MVC you're using and how it can be made to intermingle with the above, but if you want to know more about how EF was envisioned to work you should look into the technologies I've listed above.

Related

Any tool to autogenerate View Models from Entity Framework Domain Models?

I am using MVC3, ASP.NET 4.5, C#, MSSQL.
I need to create ViewModels from my Domain Model that is automatically generated by Entity Developer.
Once I create the relevant ViewModel for an entity I can comment out non required properties for a particular View.
However there is the ongoing concern that once an entity is upgraded then the ViewModel could become out of sync, and I want to minimise the risk/effort in fixing this.
Thanks in advance.
I see the same complaint endlessly about using view models. True, they can be repetitive in nature, but copy and paste works beautifully there. If you so wanted, you could even design an interface that both your model and view model must implement, which can help you keep the two in sync somewhat. However, I think you'll find that the two will diverge more than you think.
As far as validation goes, this is also a common complaint, but it's actually a symptom of bad design. Your entity class should only have validation specific to the database, which you'll find is actually pretty sparse. Entity Framework actually does a fantastic job translating most of the properties inherent limitations to the database. For example, a DateTime property's column is set as NOT NULL by default, because the C# type itself cannot be null. There's no need to add something like [Required], because the behavior is inherent.
Other types of validations such as regex are totally inappropriate for a domain model because there's no correlation to anything happening at the database level. It's entirely for the UI, and thus belongs on your view model. I think you'll find that if you evaluate all the things you're trying to validate on your domain model, you'll find most if not all should be strictly on your view model(s) instead.

Where should I add [JsonIgnore] to prevent certain properties from being serialized?

This is a very simple Web API project. I have a data model, generated DbContext, and a controller.
When I add the [JsonIgnore] attribute to certain properties on my model classes and then later make a change to the data model, the model classes get regenerated and my [JsonIgnore] attribute is deleted. I understand why this happens and that I shouldn't be adding attributes to an auto-generated class. My question is, where should I be annotating classes with attributes, like [JsonIgnore] for use with ASP.NET Web API?
ASP.NET Web API 4, RTW
You should use view models. Basically define classes that will contain only the properties that you need to expose and then return those view models from your Web API actions. This way you don't have to worry about polluting your domain models with [JsonIgnore] attributes especially if you don't want those properties to be ignored only for certain actions. In order to simplify the mapping between your domain models and view models you may take a look at AutoMapper.
Because you say explicitly that you are creating a very simple Web API project, you might be able to get away with a simple global replace. While I was converting a project to use ASP.NET Web API, I ran into the same problem. Because I was changing the Database Schema regularly it was simply easier to return the original types rather than dynamic or strongly typed view models since the properties of the data being wrapped was constantly changing.
The properties that needed to be ignored for serialization happen to be all the Navigation Properties generated by EF. It also happens that all these properties are virtual. I did a replace in files (scoped to only my data library project) replacing all public virtual with [Newtonsoft.Json.JsonIgnore] public virtual.
A quick and easy fix to allow testing while the project is still in development. I agree that in the end, you should probably wrap the EF models into view models, but this simple method can allow you to keep working without them for a bit longer.

ASP.NET MVC Database Views

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.

ASP.NET MVC: ViewModels versus Domain Entities

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.

Working with MVC 2.0 and the Model in a separate assembly

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.

Resources