Entity VS Model VS View Model

Entity vs Model vs View Model

Different people understand these terms a bit differently, but this is how I understand it:

Entity - object that has an identity (ID), usually comes from a database. Pretty simple class.

Model - any business object, this is a kinda broad term. It can be an entity, some custom class you've created in your project etc.. It's pretty much everything that isn't a view nor a controller/viewmodel.

ViewModel - some kind of a mediator between a model and the view. It modulates the communication between the model and the view, for instance applies validation, combines more models into one bigger object etc., for the purposes of the interaction with the specific view. ViewModel is also responsible for event handling (button mouse clicks for instance), so it exposes commands to the view you bind to (WPF).

what is difference between a Model and an Entity

I hope I've not missed your point here king.net...

Anyway, presuming you're talking about entity modelling or entity-relationship modelling (ERDs):

  • an entity represents any real world entity - e.g. student, course,
  • an entity will have attributes - e.g. student has first name, surname, date-of-birth
  • an entity will have relationships - e.g. student "is enrolled on" course (where student and course are entities with attributes and "is enrolled on" is the relationship.
  • the relationship may be "one-to-one", "one-to-many" or "many-to-many" - e.g. one student "is enrolled on" many courses and similarly one course "has" many students.
  • relationships also have cardinality

Adding relationships between entities creates a "data model". You've modeled some real world system and the internal entities/ objects in that system. Next step is to normalise it to ensure it meets "normal form".

In ERD terms, you may have "logical" and "physical" models. The logical describes the data-model in simple high-level terms that witholds the technical detail required to implement it. It represents the system solution overview. The physical model includes technical details required to actually implement the system (such as "many-to-many join tables" needed to implement "many-to-many" relationships).

Here are some tutorials on-line (though I'm sure there must be thousands):

  • http://www.maakal.com/maakalDB/Database101ERDpart1.htm
  • http://www.itteam-direct.com/gwentrel.htm
  • http://www.bkent.net/Doc/simple5.htm

I'm not quite sure what you mean by "model" and "view model" in a related context. Not sure if you may be confusing this with Model-View-Controller paradigm (MVC). Here, a model is some data component and the view represents an observer of that data (such as a table or graph UI component). There's lots on-line explaining "model view controller" or "MVC".

Hope this helps, Wayne

EF Entities vs. Service Models vs. View Models (MVC)

You never pass a view model to the service. A service doesn't even know about the existence of a view model that you might have defined in your presentation tier. A service works with domain models.

Use Auto mapper to map between view model and domain model and vice versa.

Personally, I've never heard of service models in DDD (view models for services).

What is difference between Model and ViewModel in asp.net core mvc?

As the name says, view model is very specific to the view.It will be a simple POCO with only those properties needed for the view.

Your other model class is your entity models. So if you are using EF code first approach, you need entity class definitions from which EF will generate the database tables. So basically these entity classes look very similar to your db schema structure.

By creating a view model, you are removing the strong coupling of your entity classes to the UI layer. Now your UI layer is independent of your entity classes and if you ever decide to change the data access code from EF to something else, you do not need to touch the views at all.You simply need to update the mapping part(from the view model to the data access/service layer entities)

View models sometimes looks very similar to your entity models, especially if your entity model is a simple table/class.

In your case, since your view is passing a userid and password, you need a simple view model which has only those 2 properties. When user submits the form,you can read the values and use it to build an domain entity class object as needed.

public class LoginViewModel
{
public string UserId { set;get;}
public string Password { set;get; }
}

You can use data annotations with the view models. The MVC model validation framework these data annotations to do the validations. For example, since user should enter a UserId and Password, you may decorate them with appropriate annotations.

public class LoginViewModel
{
[Required]
public string UserId { set;get;}

[Required]
public string Password { set;get; }
}

The [Key] attribute is more useful when you define an entity class. So i would not think it is needed for a view model. Remember view model is more like a UI concern. It has no idea about your underlying data storage mechanism at all.

Some of the most used attributes with view model properties are

  1. Required
  2. MinLength
  3. Range
  4. Url
  5. Phone
  6. StringLength
  7. DataType

Confused with Model vs ViewModel

Use ViewModels to simplify the View.

For instance, you might have a deep object graph with Products, Order, Customers, etc - and some information from each of these objects are required on a particular View.

A ViewModel provides a way to aggregate the information required for a View into a single object.

ViewModels also allow for things like data annotations and validation - which does not belong on your model, as your model should stay "domain-specific".

But in reality, ViewModels are nothing more than a simple wrapper for your domain objects.

Use a tool like AutoMapper to map back and forth between your ViewModels and domain models with ease.

Personally I always bind to ViewModels in my Views, never to the domain models, even if it's a single object. Why? Well I like to decorate my ViewModels with UIHints, validation, data annotations. Just the same way your domain models are enriched with domain-specific rules and business logic, so should your ViewModels be enriched with UI-specific logic.

If you simply have a object with a 1-1 representation of your domain model, you are missing the point of ViewModels.

Add to the ViewModels only, and nothing more, what is required for a particular View.

Example controller action

public ActionResult CustomerInfo(int customerId)
{
// Fetch the customer from the Repository.
var customer = _repository.FindById(customerId);

// Map domain to ViewModel.
var model = Mapper.Map<Customer,CustomerViewModel>(customer);

// Return strongly-typed view.
return View(model);
}

ASP.NET MVC - Database entities or ViewModels?

Definitely use view models in your views, and use something like AutoMapper to create view models from entities easily.

Cons:

  1. Sometimes it feels like you are duplicating code, specifically, when the view model and the entity have the exact same properties

Pros:

  1. You often need to represent an object in a simpler format (often called flattening), but you need full fidelity on the server side. This allows you to transition between the two without mucking up your domain model with presentation cruft.
  2. Aggregate roots often have a lots of value objects and additional entities that are irrelevant to a specific view, and omitting them in a view model makes it easier to work with.
  3. Your entities will have lots of two way references that are sensible in terms of an API, but create pure hell when serializing them for JSON, XML, etc. View models will eliminate these circular references.
  4. You may often use the same entity but in different ways for different views. Trying to balance both needs on one type can create a huge mess.

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

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.



Related Topics



Leave a reply



Submit