Easily create MVC ViewModels from Entity models? - c#

While working in ASP.NET MVC, I often find myself defining a basic ViewModel which all properties are but a small subset of the actual Entity model. I then use AutoMapper to transform my objects properly into and out of the Entity model. This works great, and separates my concerns nicely. However, I'm thinking that someone by now has made a tool to make this process easier! All the repetitive typing while creating my ViewModels inevitably leads to typos and some frustration.
What tools, if any, do you use to address this issue?
Thanks!
Edit: I don't mind decorating my properties with the appropriate UI hints, validators, etc. I just hate defining the same propery names again and again!

You could consider using T4 templating, see this MSDN magazine article to get started. You could create a template that uses reflection to get the properties of your Model, and generate ViewModel from this.

Related

Can we use SQLMetal Objectmodel as application object model?

Our team has just started using Sql Metal and I have been playing around with it for 2 days. While doing this, I have noticed couple of things.
When we run command like following
sqlmetal /code:ps.cs /server:devapp042dbs
/database:promotionalsponsorship /namespace:DAL
It creates a "LINQ to SQL SQLMEtal" object model. Now, this is not our regular class. It has a lot of autogenerated code and it almost smells like LINQ/EF with a lot of autogenerated properties and methods.
I have used Micro ORMs like Dapper and ORMLite from Service stack and the onderful thing about those is that it works with the simple objectmodel that we have created rather than auto-generating its own object model.
My question is that can we use these SQLMetal mapping classes as our Models of the application or we have to create a simple wrapper class around it using which we can extract all the information that we need to.
To clarify my point following are the samples of what I call a SQL Metal Class and a simple model class
Although this question would possibly be closed, as the answer is subjective, the short answer is yes, it is perfectly valid to use such autogenerated set of classes as your model. There are plenty of succesful apps built this way.
Since these classes are partial, you can even extend your domain model by adding custom properties/methods/events.
If you are concerned that the autogenerated code is not clean enough, consider the code first approach of the Entity Framework, nHibernate or any other ORM that supports this scenario. This way you start from a clean POCO model and just define its mapping to a relational structure.

When should I query from a database in my view, ASP.NET MVC

Problem:
If I have a scenario where I don't want to change my model properties and need to get one more attribute from some table, is it fine if I write a query inside a view and show the result?
If the answer is no, I would like to know why it's not considered a good way.
In my opinion you should never do that. Just because you loose the entire paradigm of the tool you are using.
In a few years, this is confusing to you, or someone else maintaining the code. If you don't want to change it all, use dynamic properties, ViewBag or other options to keep your flexibility, test-ability, etc.
Yes.
View is not a mirror of your data structure. Actually, often it's an
aggregation and/or manipulation for user-friendly presentation of the data that stands behind.
In my opinion, you should never do queries in your Views. It's called MVC and the proper way of using it is to separate concepts.
You should have a Model, a Controller, a View and a Repository (as the simpliest approach). As the name suggests, View must be used only for displaying processed data.
More information about MVC best practices is here.
I remember when I started working with MVC. I didn't know about this and my teamleader told me it's never a good choice to do this.
Conclusion:
It's just a matter of design and perspective. If you're doing a project for yourself or for the university, organize your code as you wish. If you're working in a professional environment you should respect some working principles
Another important factor to think of, is this: if another person must refactor or modify your code he must know where to find methods, where to find models and so on.
First of all, the reason why it's called MVC is because of the separation of concerns. View's are only concerned of the User-Interface. Queries are done on the controller. Another is it would be too confusing if you would place everything in a single page which already defeats the purpose of having MVC.
Though there are cases when querying the database from a View may seem easier and appropriate, you should be ready for the consequences of breaking separation of concerns (SoC). When you spread your DAL across many layers it's going to be hard to re-factor the database in the future. Another question is security - if you decide to implement database security or controller-based security later, your view-based queries will be a security point.
However, if the project is small, I would trade SoC for performance.

What is the relationship between domain models and view models? Do they need to be separate? (Does using EF complicate this?)

So my programming background is very self-taught and sporadic. I am working on an MVC4 project and am trying to focus on best practices rather than just functionality.
The general sense of the project is a report generator. So I am trying to understand what exactly Domain Model vs View Model are, and how they related to the models used for CodeFirst Entity Framework. Any tips are appreciated.
From my understanding, let's say my Report object has multiple properties, but for the view I only want a user to be able to edit certain properties, then the ViewModel would be something that maps between the Report object and the user input?
Sounds like you've got the right idea. A ViewModel is the View representation of the domain entity. This can be applied to both data coming in and data going out of the model.
But, the extra layer (and mappings) also increase complexity of the code. You now need a view model class, a mapper class, and a domain entity (EF). So, if you can build what you need without this extra layer, then keep it simple. Domain models and domain modeling should only be used for a business domain that is significantly complex.
Yes your understanding is correct.
View model is data object used by your view. It contains properties necessary either for showing some data to user or collecting data from user. Those properties doesn't necessarily be only data. For example you can have some properties used to control if any field in the input form will be enabled or disabled.
Domain model on the other hand is object used for your logic and persistence. Again it doesn't necessarily contain only persisted properties. There can be other properties computed from persisted properties and there can be also methods working on top of properties.
In some very simple scenarios view model and domain model can be represented by the same object.
This is what I've seen in a few examples, what I've used for the last couple years and feel comfortable with, and was also the pattern already in use by a preexisting MVC team when I came into my most recent job.
Basically entity framework, or whatever ORM your using, will have Entity classes. These are either simple POCO's or something heavier with some ORM's. The goal is for the relationships between entities to closely resemble reality, and as such they are in a way your "Domain models". Either way, you will often find that you're view needs to either flatten properties from child/parent objects, or as you mentioned, only display certain fields.
Often times you will also need additional fields on the view model. For example, the options for a dropdown list, as these aren't part of the entity(only the foreign key that indicates which item is selected is in the entity, but not the list of items from which the user can select).
So unless your view is simple enough to be able to use the #model of your EF entity, often times you may need a ViewModel(VM) class. Some people have a different VM for each view. I personally try to reuse my VMs. Usually a PersonSummaryViewModel which is just a few fields good for things like select lists or indexes where space is limited and I will only display important fields, and a PersonViewModel which are all the fields from the entity, as well as fields for items for dropdown lists(but when used on a readonly page those are simply left null).
Personally I like to name things PersonVM and PersonSummaryVM but others prefer more verbose naming of PersonViewModel. EF will give your entities names like Person, but I've seen other ORM frameworks suffix all of the classes with Entity so you have PersonEntity. I've come to be fond of the Entity suffix personally.
If your database is well designed, it is likely that your entity classes are pretty close to what some would consider your domain model.
We have classes that expose static methods which we call to retrieve data. The controllers have little to no database code in them, and instead all of that are in static methods like PersonModelFactory.GetList(), PersonModelFactory.GetSingle(int id), .Save(PersonVM person) which are responsible for querying the database, and populating the data from the entities into the view models, and then returning a view model. These methods also perform certain validation(beyond what basic things you can do with data annotations on your view models), and other business logic IF it is something that should occur in tandem with whatever database modification is occurring. There's more to the implementation details involving interfaces and generic parameters that are aimed at making these methods very reusable but it is a little complicated for the scope of this post. We've actually successfully reused these classes from both web forms and MVC, so they've proved there re-usability. Some people wouldn't like the fact the DB access, mapping, and business logic/validation occurs in the same layer, but since the DB modification shouldn't occur unless validation passes, we felt it was important for these things to be atomic and mutually dependent.
It is probably more common for people to use the "repository pattern" for database access layer with MVC, and there are even scaffolding for MVC to generate these classes for you. However, these generally won't handle mapping or business logic.
Either way, the main goal is reuse and minimizing the clutter in your controller actions. Before adopting the factor pattern I mentioned, I found my controllers becoming cluttered. I saw opportunities for code to be reused between actions, and thus I was creating private methods in the controller. I really like the factory pattern the team I'm on now uses alot more.
You will definitely find many variations of how people use view models and repositories.
I cannot recall having seen any articles or examples that speak specifically about "domain models" in the context of MVC. IMO domain modelling is part of the requirements gathering process, and then the design of the database/entity framework will reflect the results of those findings. Given limitations of time/resources/complexity you may simplify the domain model. There are frameworks that deal with things like domain languages and what not, I don't think that kind of thing is very common.
Before there were ORMs, there were people doing alot of mapping manually between the database layer(consisting of command objects running SQL), into "business objects" which were often POCOs, basically what you have as EF entities, but sometimes they had some business validation/logic incorporated somehow. Now I don't hear people talk about "business objects" hardly ever because the purpose that layer served has mostly been replaced with EF, and the business logic is either in controller actions or in some other service layer.
Over the years, one thing is certain, what "view model", "business model", "entity", and "domain model" mean to different people will vary.

Acceptable to use domain object definition in razor view?

I'm currently developing a multi-tiered application, using MVC3 and Spring.NET all of which is going well. I have one question with regards to razor, and assigning a model to it. For instance, my definition for say, Member is in the Domain layer, is it acceptable to decorate the fields with Data Annotations here, and use this directly in the views? It seems to go against the separation of concerns to a certain degree.
That being the case, what would be the best way to do it? Redefine the required classes in the Model, and use them there?
Any suggestions/recommendations would be greatly received.
R.
A standard approach here is to use ViewModels and to annotate these with the validation attributes that apply to the presentation layer. With this approach, you would map the domain object properties to properties on the ViewModel; a library like AutoMapper can really help to reduce duplicating code all over the place in this regard.
Sometimes you may find that all your ViewModel does is simply wrap the domain object. In these instances I still think that this is a good thing to do as it allows you to add any presentation functionality to the ViewModel that is specific to the model and context, an option you don't have if you map the domain object straight to the view.

Proxy object references in MVC code

I am just figuring out best practice with MVC now I have a project where we have chosen to use it in anger.
My question is.
If creating a list view which is bound to an IEnumerable is this bad practise?
Would it be better to seperate the code generated by the WCF Service reference into a datastructure which essentially holds the same data but abstracts further from the service, meaning that the UI is totally unaware of the service implementation beneath.
or do people just bind to the proxy object types and have done with it ?
My personal feeling is to create an abstraction by creating a model and placing the Collection in that and referring to the collection in the UI code from the model.
but this seems to violate the DRY principle with respect to proxies.
Well, the best practice is to use a View Model which is populated from the Model. In many cases they could be the same because the view shows all the properties returned by the service, but another view could show only a subset of them. That's why having a view model is considered a good practice. This view model can also contain some calculated properties that are specific to the view. To further simplify the mapping between those objects you could use AutoMapper. There's also a nice article you may take a look at explaining the concept of view models.

Categories

Resources