Any tool to autogenerate View Models from Entity Framework Domain Models? - asp.net-mvc

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.

Related

What is the best practice, Entity Framework Models or MVC Models?

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.

EF 4.1 Code First - What pattern should I use?

I am learning EF Code First and I am struggling a bit with what patterns to use in my application. I have read many conflicting sugestions and arugments some stating you should use the Repository pattern while others say doing so is redundant, which I tend to agree.
Here is my delima:
Suppose I am building a REST Web Service that is going to allow me to manage customers. This service will allow me to add customers, delete customes, and edit customers, and find customers.
Should I:
A.) My question comes down to where should my business logic go. Should I have a CustomerManager class that provides Add, Edit, Delete, and Find methods that take in a Customer entity? Should my validation logic go in those methods?
B.) Should I use an Active Record style of development when my Customer entity would have Save(), Delete(), and Find() methods on it withall validations login being done inside of the Customer class?
C.) Should I do some type of hybrid, where simple validation logic is on the entity itself. This could be done through code first attributing. I could also have a simple save method on the entity. Then, I could do complex business validation logic, deletes(), finds(), and multi-entity saves in a CustomerManager class?
I kind of lean toward option C. In the past I have typically used Manager/Service classes keeping my entities pretty simple. However, since code first does entity property validation on the entity level, it seems like maybe all simple entity validation should go there.
I realize this could be somewhat of a religious topic, but I would like to get some other options on what would be the best way to put together a solid application.
EF 4.1 Code first combine unit of work with data mapper pattern.
So, I would not recommend use active record pattern.
Repository pattern with entity framework is common solution. If you want some simple validation logic, you can use DataAnnotations which works with entity framework well.
Here is simple example of implement repository pattern with EF :
http://www.efekaptan.com/repository-pattern-with-entity-framework-code-first-4.1

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.

Using ViewModel in ASP.NET MVC with FluentValidation

I am using ASP.NET MVC with Entity Framework POCO classes and the FluentValidation framework. It is working well, and the validation is happening as it should (as if I were using DataAnnotations). I have even gotten client-side validation working. And I'm pretty pleased with it.
Since this is a test application I am writing just to see if I can get new technologies working together (and learn them along the way), I am now ready to experiment with using ViewModels instead of just passing the actual Model to the view. I'm planning on using something like AutoMapper in my service to do the mapping back and forth from Model to ViewModel but I have a question first.
How is this going to affect my validation? Should my validation classes (written using FluentValidation) be written against the ViewModel instead of the Model? Or does it need to happen in both places? One of the big deals about DataAnnotations (and FluentValidation) was that you could have validation in one place that would work "everywhere". And it fulfills that promise (mostly), but if I start using ViewModels, don't I lose that ability and have to go back to putting validation in two places?
Or am I just thinking about it wrong?
Or am I just thinking about it wrong?
Probably ;)
If you add all the validation code to your ViewModels you'd just be validating them instead of your actual Models. All your really changing is which objects can enter an invalid state.
Right now I'm happy as pie only validating ViewModels and then passing that information back to the actual Models and DAO layers. Whether or not your domain can enter an invalid state is a contentious topic though but so far this technique is working great for me. Validation in one place and no invalid objects in my persistence store.

Why it's not a good idea to pass entities as Models in MVC?

We're developing a pretty large application with MVC 2 RC2 and we've received some feedback on the way we're using the Entity Framework's Lazy Loading.
We're just getting the entities in the controller and sending them as models to the Views, that is causing that the view code asks the Database for the navigation properties we are using in it. We have read about this and it appears is not a good design, but we were wondering why?
Can you help us understand this design problem?
Thanks!
The main issue here is coupling. The idea behind a model, which is the "M" in "MVC", is that it has no external dependencies. It is the "core" of your application. The dependency tree of a well-designed app architecture should look something like this:
+---------------------------------------> Views
| |
| |
| v
Controllers ----+-> Model Transformer -----> View Model
| \ |
| \ |
v \ v
Data Access <---- Persistence --------> Domain Model
| /
| /
v /
Mapper ------+
Now I realize it's not exactly convincing to just say "here's an architecture, this is what you should use", so let me explain what's happening here:
Controller receives a request.
Controller calls out to some kind of persistence layer (i.e. repository).
Persistence layer retrieves data, then uses a mapper to map to a domain model.
Controller uses a transformer to change the domain model into a view model.
Controller selects the necessary View and applies the View Model to it.
So, why is this good?
The domain model has no dependencies. This is a very good thing, it means that it's easy to perform validation, write tests, etc. It means that you can change anything else anywhere in your architecture and it will never break the model. It means that you can reuse the model across projects.
The persistence layer returns instances of the domain model. The means that it can be modeled as a totally abstract, platform-agnostic interface. A component that needs to use the persistence layer (such as the controller) does not take on any additional dependencies. This is ideal for Dependency Injection of the persistence layer and, again, testability. The combination of persistence, data access, and mapper can live in its own assembly. In larger projects you might even be able to further decouple the mapper and have it operate on a generic record set.
The Controller only has two downstream dependencies - the domain model and the persistence layer. The model should rarely change, as that is your business model, and since the persistence layer is abstract, the controller should almost never need to be changed (except to add new actions).
The Views depend on a separate UI model. This insulates them from changes in the domain model. It means that if your business logic changes, you do not need to change every single view in your project. It allows the views to be "dumb", as views should be - they are not much more than placeholders for view data. It also means that it should be simple to recreate the view using a different type of UI, i.e. a smart client app, or switch to a different view engine (Spark, NHaml, etc.)
Now, when using O/R Mappers such as Linq to SQL or Entity Framework, it is very tempting to treat the classes they generate as your domain model. It certainly looks like a domain model, but it is not. Why?
The entity classes are tied to your relational model, which over time can and will diverge significantly from your domain model;
The entity classes are dumb. It is difficult to support any complex validation scenarios or integrate any business rules. This is referred to as an anemic domain model.
The entity classes have hidden dependencies. Although they may appear to be ordinary POCOs, they may in fact have hidden references to the database (i.e. lazy loading of associations). This can end up causing database-related issues to bubble up to the view logic, where you are least able to properly analyze what's going on and debug.
But most importantly of all, the "domain model" is no longer independent. It cannot live outside whatever assembly has the data access logic. Well, it sort of can, there are ways to go about this if you really work at it, but it's not the way most people do it, and even if you pull this off, you'll find that the actual design of the domain model is constrained to your relational model and specifically to how EF behaves. The bottom line is that if you decide to change your persistence model, you will break the domain model, and your domain model is the basis for just about everything else in your app.
Entity Framework classes are not a domain model. They are part of a data-relational model and happen to have the same or similar names that you might give to classes in a domain model. But they are worlds apart in terms of dependency management. Using classes generated from an ORM tool as your domain model can only result in an extremely brittle architecture/design; every change you make to almost any part of the application will have a slew of predictable and unpredictable cascade effects.
There are a lot of people who seem to think that you don't need a cohesive, independent domain model. Usually the excuse is that (a) it's a small project, and/or (b) their domain model doesn't really have any behaviour. But small projects become large, and business rules become (far) more complicated, and an anemic or nonexistent domain model isn't something you can simply refactor away.
That is in fact the most insidious trait of the entities-as-model design; it seems to work fine, for a while. You won't find out how much of a mistake this is until a year or two down the road when you're drowning in defect reports and change requests while desperately trying to put together a real domain model piecemeal.
One potential issue with this design is that the view might iterate through the model objects (that are lazy loaded) more than once and cause an unnecessary overhead. For instance, if a Web page displays the same data in two different forms in a couple of different locations in the page, it'll loop through the query twice and causes two round-trips to the database (Look at the tags under the question and in the sidebar on this page and assume they came from a single query). The view could deal with this problem by caching the results once and loop twice on the cached data, but this is not what a view should deal with. It should present the data given to it without worrying about these stuff.
The problem is that your UI is tied more directly to your entity than necessary.
If your entity is encapsulated by a ViewModel, then your UI can not only contain the entity (the data it wishes to eventually save), but it can also add more fields and more data that can be used by the controller to make decisions, and be used by the View to control the display. In order to pass the same data around outside of a ViewModel would require that you use action method parameters and ViewData constructs, which does not scale, especially for complex ViewModels.
The view is stupid and ignorant. It should not and doesn't want to know anything. Its very shallow and focusses only on display. This is a good thing, as the view does what it does best.
By doing it your way, you leak, what should be data concerns, to the view, and furthermore you limit you view only to recieve data from your entity as the strongly typed model.
Furthermore you let you dependency on EF go all the way to the view and penetrates you app, where you should try to be as loosely coupled to that dependency as you can.

Resources