ASP.NET MVC - view model, domain model and data model [closed] - asp.net-mvc

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am using entity framework in my latest ASP.NET MVC 3 project. As it is DB first, the entity framework generates Database models. In my service (business) layer I Scaffold (MvcScaffolding) to generate service methods, views and controllers. Scaffolding also generates the domain models. When binding these models to the Views, I use view models.
In short, I ended up in using three types of models. Is this Ok? The view models are kept in the Presentation layer, domain models are kept in the business layer and data models are kept in the repository layer.
Please let me know your thoughts.

That sounds fine and indeed has several benefits.
You can recreate your database models from scratch without affecting the domain models, except how they are mapped of course. Some would argue that these two could be merged into one but it deeply depends on your setup.
Separate view models will allow you more freedom to change and create new viewmodels to suit your views. It also helps preventing late loading proxies etc.
Many people would also have a Dto set of objects. These come in useful as a set of objects for caching and also if you have more than one UI, say a windows service as well.
Automapper is very popular to ease the pain of having so many models to map.

It is good when you have differences between models on every level. If all you do with this models is put data from one layer model to another layer model without any transformation and processing, you can remove redundant models. In common cases domain model becomes redundant.
You should create separated viewmodel and database model due to necessity to have a possibility to recreate database model from database without changing of views.

Related

Mapping violation of DRY principle? How to separate layers in ASP.NET MVC app [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I am the lone developer on a new ASP.NET MVC project, so my ability to discuss design with peers is limited. I'd like to ensure that any change to my app in the future is confined to the layer being changed, so that the whole app doesn't have to change at once.
I'm planning to have 3 layers, each in it's own project, consisting of data layer, service/business layer, and presentation layer.
My data layer will use Entity Framework with a generic repository. This layer will return Entity types from the repo methods.
My service/business layer will be thin, but I wanted a nice separate place for business logic down the road. In the beginning, it will be nothing more than service classes for each of the major areas of my app. ie EmployeeService provides CRUD methods related to Employees that call upon the data layer. At some point, I may replace it with a Web API service layer and serve many clients.
My presentation layer will be ASP.NET MVC, with ViewModels and strongly typed views. Down the road, there may be additional clients.
I'm most interested in the communication between layers and project structure. My initial thoughts were to map data layer Entities to service layer Business Objs/Domain Objs or DTOs using AutoMapper, then mapping again to ViewModels in presentation. The mappings in the beginning would be mostly 1:1 though, so it feels redundant.
Is it a violation of DRY to have a DTO that is the same as the Entity class? That's the only way I know how to decouple from my database structure. Ideally, if I make a database change, I want to only have to change the Entities and the mappings. ie, I totally rearrange how I'm storing something and I have all new entity classes/relationships... I'd like to map the new data implementation back to the same DTO and higher layers never know.
The same repetition feeling comes up when mapping from service layer to presentation layer. My DTOs will get mapped to ViewModels. It's mostly the same stuff, but my thinking was that ViewModels also contain UI implementation details like sort fields and UI specific types like SelectListItem.
So is this actually repetition or does it just feel repetitive? Is there another way to accomplish my aim of isolating changes in layers? I'd like to be able to change or replace presentation, service or data layer with relative ease.
I recommend finding a solid (and SOLID) open source MVC project and follow that pattern. No need to re-invent the wheel -- .NET MVC is robust and there are plenty of projects that follow SOLID principles.
Take a look at NopCommerce, you can get the source code and you will see a well-architected app that answers many of your questions

Is it advisable to have "pure" model objects additionally to managed objects? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have seen in some (REST) iOS apps that they use "pure" model object, e.g. "Product", core data object, e.g. "ProductCore", and an object to represent the remote objects e.g. "ProductJSON".
I myself usually also use this architecture, I think it leads to clear separation of concerns. It has also some practical benefits, for example there are situations in which I want to create a model object but not add it to core data yet. Or others where I want to send the models directly to the server and not store them in core data.
On the other side, it consumes more memory and I have to maintain more classes. It's also not necessary for a memory cache as core data has one. Temporary objects (e.g. form data which hasn't been validated yet) can also be deleted without performance issues, as managed objects are only in memory until saved. There are also not portability benefits, as anything that understands Swift/ObjC also understands core data... extensibility can be achieved at least with extensions. Maybe subclassing.
So I was wondering, is there an overall preferred way to setup model clases in applications? In which context does an additional layer with pure model objects make sense, where is it an overkill?
Edit: I don't consider this an "opinion based" question. The optimal architecture can be different depending on the requirements, but which is one better under which circumstances should be able to be determined based on facts.
I am not sure what is meant by a pure object. Here is what I am doing:
Service model represents the data sent to and received from web services, and corresponds to their JSON payloads. I write adapters to map JSON to service models and vice versa.
Entity models represent persistent data. These are the Core Data classes corresponding to my data model, and inherit from NSManagedObject.
View models represent data displayed in a view. Each view has its own view model. This approach maps the view model precisely to the view. An adapter class builds the view model from entity models and/or service models (if the data to be displayed is not persistent). The adapter shapes the data to the view, and does things like formatting dates to simplify the job of the view controller.
A table view cell, for example, might display elements from several entity models. The view model would contain a class representing the data to be displayed in each cell, and the adapter would build one for each cell. Populating the table view cell in the view controller becomes a very simple task of mapping one-to-one between view model and cell fields.
This approach might seem overkill, but I have found it to be extremely effective and worth the effort. It greatly simplifies the code in the view controllers, and makes testing easier.

Developing Data and User Models :: Tools / Best Practices / Approaches [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm finding that it's difficult to clearly articulate the specific models I want to create at times - especially as projects get bigger and I have to wrap my head around the relationships between everything.
How do you organize your data and user models? Do you sketch them out on paper? Maybe there's a neat tool online?
Yep, I believe good old pencil and paper are the tools to use for that. Keeping in mind that eventually your models will access the database through an object relational mapper, you should think in relations.
Mostly, it is worthwhile to think in relations first and then figure out names for your models. Consider the following case where you need something that stores the following:
posts need to be stored
comments need to be stored
users have to be stored
Now, before you think about how you name each of these, rather think about how they are related. I find that mostly by doing that, you will choose the right names intuitively:
A post belongs to a user, a user has many posts, a comment belongs to a post, a post has many comments, a user has many comments, a comment belongs to a user.
In this last rather intuitive sentence, you have everything you need: names and relations. Rails supports this intuition because it is so idiomatic.
This is as far as planning databases and models goes - if you have an existing application and need to figure out the models' relations, I recommend using a UML (unified modelling language) gem called railroady, which will automatically create a nice graphical overview of your application's data.
I find visualisation to be a huge help in establishing a data model and working on data flow diagrams etc.. Pencil and paper has never worked for me because I get all neatness obsessed and hate making changes and redoing things, and I also don't want to get distracted by moving little boxes around on a screen to make them look nice as it breaks the "creative flow".
I've used GraphViz http://www.graphviz.org/ for this in the past for a number of reasons.
First, I've worked for a lot of companies too cheap to spend money on any software that might accidentally help software development.
Secondly, the text input is distraction free -- it lets you concentrate on content without the distractions. The text input can also be generated by code, so it's been great for (semi)automatic code and schema visualisation.
Third, the input text can be added to the source code repository and commented and change-tracked.
I recently discovered http://graphviz-dev.appspot.com/ which has made it even easier -- don't forget to click on them ad links.

Why Asp.net MVC and not Asp.net MVP [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As far as theory goes it seems that Asp.net MVC framework could better be described as an MVP software pattern... Why not?
Because as it seems to me I see Asp.net MVC as a framework that has functional views (scripts running) that invoke controller actions. So it seems views are masters.
There are two distinct differences (taken from source):
Passive View:
The View is as dumb as possible and contains almost zero logic. The Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View.
Pro: maximum testability surface; clean separation of the View and Model
Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller:
The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
Pro: by leveraging databinding the amount of code is reduced.
Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.
See this question: What are MVP and MVC and what is the difference?

Couple of questions about asp.net MVC view model patterns [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm new to MVC.
I have read this short bit detailing three ways of dealing with the view model in MVC:
http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx
The gist of it seems to me that:
Method 1, pull an object out the database and use it as your view model. Quick and simple, but if you want data from multiple tables you're totally screwed (I can't think of a way around it without Method 2).
Method 2, create a class that has references to multiple objects, and use this as your view model. This way you can access everything you need. The article says that when views become complicated it breaks down due to impedance mismatch between domain/view model objects... I don't understand what this means. Googling impedance mismatch returned a lot of stuff, the gist of it being that you're representing database stuff using objects and stuff doesn't map across cleanly, but you'd presumably have this problem even with Method 1. Not sure what I am missing. Also seems to me that creating a class for each View to get the data you want isn't ideal from a maintenance point of view, not sure if you have a choice.
Method 3, I am still getting my head around it, but I don't quite understand why their checkbox example wouldn't work in method 2, if you added a bool addAdditional to your class that wasn't connected to the domain model.
Method 3 seems to say rather than return the domain stuff directly, just pull out the properties you specifically need, which I think is nicer but is gonna be harder to maintain since you'll need some big constructors that do this.x = domain.x, this.y = domain.y etc.
I don't understand the builder, specifically why the interface is used, but will keep working on it.
Edit: I just realised this isn't really a question, my question is, is my thinking correct?
The problem I've run into with #2 is that I have to do one of these two things:
Include every single field on every single object on the form -- those that aren't going to be displayed need to be included but hidden.
Only include the specific fields I need but use AutoMapper or something similar to map these fields back onto the actual objects.
So with #2 I see a mismatch between what I want to do and what I'm required to do. If we move on to #3, this mismatch is removed (from what I understand, briefly glanced at it). It also fixes the problem that a determined hacker could submit values like id fields or similar when using method #2 that unless I was very careful could be written to my data store. In other words, it is possible to update anything on any of the objects unless one is very careful.
With method #3 you can use AutoMapper or similar to do the dirty work of mapping the custom object to the data store objects without worrying about the security issues/impedance exposed by method #2 (see comment for more details on security issues with #2).
You're probably right about impedance mismatch being present in both Methods 1 and 2 - it shows up anywhere you're going between objects in code and DB objects with relational mapping. Jeff Atwood writes about it, and cites this article, which is a fantastic discussion of everything dealing with Object-Relational mapping, or "The Vietnam of Computer Science". What you'll pretty much end up doing is weighing the pros and cons of all these approaches and choose the one that sounds like it fits your needs the best, then later realizing you chose the wrong one. Or perhaps you're luckier than I am and can get it right the first go 'round. Either way, it's a hairy problem.

Resources