Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

ASP.NET MVC - Database entities or ViewModels?

I am currently working on an ASP.NET MVC project.

Some developers on the team want to bind the auto-generated database entities directly to the Views.

Other developers want to create tailor-made ViewModel's and bind those to the Views.

Objectively, what are the pros and cons of both approaches?

(By "database entities" I am referring to the auto generated classes that an ORM framework generates, such as LINQ to SQL, Entity Framework or LLBLGen).

question from:https://stackoverflow.com/questions/10928287/asp-net-mvc-database-entities-or-viewmodels

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...