Pages

Men

rh

7/16/2013

Why(s) & How(s) of Asp.Net MVC Part 2

Introduction

I know its been a while I wrote the part 1. You probably read lots of resources about Asp.Net MVC by now. Thus for now I will skip how to do part and concentrate more on why. Also as we go with series will demonstrate some exciting new features that are available to Asp.net MVC. Please remember wherever in this post I mention MVC, it refers to MVC 4. In this post, we will will limit our discussion on Model. Why model is used, what approach to take while working with models and validating them. 

MVC on Asp.Net  

Sounds bit old and out of scope topic, but even now I see lots of discussion on how web form developers are planning to migrate to MVC. Its been a hot topic, hence I like to share some of insights in this regards. For new developers MVC is a charmer, but for those who are considering to migrate from webform to mvc primary concern is familiarities of feature that's they used over the years. Most of the webform developers concerns is Asp.Net webform framework has lot to offer in the context of, 
  1. Security 
  2. Debugging 
  3. Validations 
  4. State management 
  5. MasterPage/UserControl 
  6. RAD Controls 
  7. Familiar Syntax 
Now common question is does Asp.Net MVC fulfill these needs? does it?


 
Humm, lets look what Asp.net MVC has to offer.Even though their architectural approaches are quite different, ASP.NET MVC and Web Forms actually have a lot in common.

ConcernsAsp.Net MVCWeb Form
Securityforms/windows Authentication, MemberShipforms/windows Authentication, MemberShip
ValidationData AnnotationsServer Controls for Validation
State ManagementSession and profile stateView State/Cookies/Query Strings
Cross Page Data Transfercontroller to view/controller to request ViewData, VieBag and TempDataSession/Query String
Health monitoringHealth monitoringHealth monitoring
Cachingoutput and data cachingoutput and data caching
Master PageLayout PageMaster Page
UserControlPartial ViewUserControl
RAD ControlHTML helperServer Controls
SyntaxRazor View EnginesASPX View Engines

Bingo , as you can see a Web Forms developer looking to learn the ASP.NET MVC already further ahead than he think. Productivity wise asp.net web forms and MVC do not differ much, one can obviously raise the issue of raid controls. I agree raid control speed up the development but think how UX designers can play with views without developers involvement, developers do not have to give their effort to implement cool UX utilizing RAD controls. combining these final development effort difference is very thin between webforms and mvc. Moreover there is lots of good framework like angularJs/backbone js available these days to ease development effort.  As productivity is the one of the major concern for developers who wish to move from web forms to mvc.


 
This is no surprise like Web Forms, ASP.NET MVC is built on top of the ASP.NET platform. So both frameworks rely on the .NET languages of C# and Visual Basic .NET to interact with the .NET Framework, and can access compiled assemblies developed with any other language that the .NET Framework supports. Even interesting is while developing with MVC you will see very familiar web.config and Global.asax. If you google probably will get thousands of resources on these comparisons.  

Working with Model

Now you can ask the obvious question, DB, Model or Code first what is all this and how this is related to MVC? fair enough, but too answer that lets step a back for a while to part 1 which discuss model part of the MVC. Lets refresh our memory

        Models are those parts of the mvc application that plays with application's data
        domain and retrieve/store model state in a database.
 
So model is the heart of your application (from a business perspective) that deals with single most important element "data". Model represents your data structure and will contains functions that will help you to do CRUD (Create/Retrieve/Update/Delete) operations. Now depending upon the architecture, application type/scope, risk analysis we need different approach to implement model entity. This is where EF (Entity Framework) came in play.With EF we have flexibility to work with model as we want to. 


Entity Framework provides three ways to define the model of your entities. Using the database first workflow, with the model first workflow, and last not least code first approach. Code first approach of designing the model is becoming popular choice due to complete control over the classes being written or Implemented. But that doesn't mean DB first or model first is absolute or not coll to use. Trick is to know when to use what, if you can analyze your application scenario/scope/risks and choose which is prefect for your scenario, in my opinion that is cool. Lets dive to our main topics.

Why Database First

Consider a scenario where an existing enterprise databases tend to have many tables, each with many columns. They are not normalized as you prefer but cant complain its an existing database. No one will allow you to break and restructure the DB when there a business in stack. In this situation the entity model of your application must compatible to the existing database; you can’t bend the database to suit your preferred object model, in other words your hands are tied. Database First is popular in scenario like this, also called “brown field” scenarios with developers who build applications that access existing production databases holding large numbers of tables and columns.
 
 
When to adopt DB first approach has different opinion over forums, groups, user meetups. Despite of reinventing the wheel I like to summarize those and here is the list,Legacy systems built upon existing DB DB designed by DBAs, developed separately or if you have existing DB. 
  1. You will let EF create entities for you and after modification of mapping you will generate POCO entities.
  2. If you want additional features in POCO entities you must either T4 modify template or use partial classes.  
  3. Database defines your domain model. 
  4. A fair amount of business logic's are to be resides in Database end for better maintainability.
Now question is is this bad to use DB first? Many experts got their own view, my opinion is despite of non comforting object model if the application is serving as it supposed to be, then there is no reason to be unhappy about it. Every approach we are discussing here has its own pro & con's.

Advantages

  1. RAD development approach, EF will include all the usual metadata of existing database, CSDL, SSDL and the mapping between them just as model-first does. 
  2. Can concentrate on DB design first in case dealing with big volume of data.
  3. Database is not just a storage, can utilize to implement business logic's also.

Disadvantages

  1. No control over EF generated codes 
  2. EF generated codes are too complicated to customize
  3. Less control over the EF generated entities
  4. Impose of custom Entity level validation will require expertise on T4 template

Why Model First

Though DB first approach was the successor, but changed development scenarios demanded Domain Driven Development, though model first brings essence of DDD but not truly. The Model first design came into prevalence where the Database Schema was based upon the Model. Though conceptually db & model first approach is different but from implementation perspective there in not much difference. Both ends up with generating lots of auto generated codes.

 
Just like DB first When to adopt DB first approach has different opinion, my summarized version is,
  1. IMHO popular if you are designer fan (= you don't like writing code or SQL). 
  2. You will "draw" your model and let workflow to generate your database script and T4 template to generate your POCO entities. You will lose part of control on both your entities and database but for small easy projects you will be very productive. 
  3. If you want additional features in POCO entities you must either T4 modify template or use partial classes. 
  4. Manual changes to database will be most probably lost because your model defines the database. This works better if you have Database generation power pack installed. It will allow you updating database schema (instead of recreating) or updating database projects in VS. 

Advantages

  1. Database is not just a storage, can utilize to implement business logic's also
  2. Flexibility of creating entities that make sense in your business domain and their relationships
  3. Minimize the "ripple" effect caused by changes in the object model (code) generated or the database.  

Disadvantage

  1. the contents of the database will be generated each time causing data loss as it regenerates everything every time you create the database from the model.  
  2. once the database schema is published database can be changed directly in many occasion and thus the model becomes out of date and must be updated from the database in a database-first style

Why Code First

In Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Ideal candidate for Domain-Driven Design (DDD). Code First uses classes and properties to identify tables and columns, respectively. Code First has a number of benefits. First, developers are no longer delayed by not having a database. You can now create the database structure and start coding, with everything maintained in the same solution. Second, there's no auto-generated code; a developer has full control of each of the classes. Lastly, everything is kept simple in the data access layer because there's no .EDMX model to update or maintain.

Advantages 

  1. Can integrate model validation easily 
  2. EF modelling often has weird errors, such as when you try to rename an association property, it needs to match the underlying meta-data - very inflexible. 
  3. Contrast back to Code first and you have complete control without all the hidden complexities and unknowns to deal with. 
  4. Enable migrations can keep track of schema changes, so can seamlessly deploy upgrades/downgrades while model changes.
I am fan of code first so I guess, my opinion on disadvantage is biased

Disadvantage

  1. No visual model designer (EDMX) support
  2. No auto generated codes
  3. Manual changes to database will be most probably lost because your code defines the database.


 
There is no hard and fast rule when to use code first, but in general you can use code first,

  1. Full control over the code (no auto generated code which is hard to modify).
  2. Ideal for application with complex business needs
  3. Very popular because hardcore programmers don't like any kind of designers and defining mapping in EDMX xml is too complex.  
  4. If you are expecting that role of the database in your application is only storage. EF will handle creation and you don't want to know how it do the job.

Model Validation 

As we discussed on above 3 approaches model objects deals with data and perform the business logic on that data. Models are application specific and hence asp.net framework impose no restrictions on the constructions of model objects. But one can impose the custom validation on models. Most common and convenient approach to add such validation is code first because this approach ensure complete control over model and 2 popular method of validation is DataAnnotation & FluentValidation. DataAnnotation and FluentValidation are both serve similar purpose. They ensure that the values that have been assigned to the object properties satisfy business rules that is supposed to apply.

DataAnnotationFluentValidation  
validation support built-into the .NET Framework and can integrate with minimal code.advanced validation support that is not possible with data annotations
Not intend to work with DB/Model first, but with some workaround (buddy class) supports.Supports only Code First approach

Does that means db first or model first approach do not need any model validation? While using the db first or model first the EDMX file has the same purpose - it contains all the details and mapping definitions of your model. whatever restriction (or can say constraints) you define your database/database model is translated by EDMX mapping definitions, so you do not have put extra effort to define your own. Fluent API or data annotations and conventions replaces the EDMX file only when using Code-First.

Source Collected from codeproject.com

No comments :

Post a Comment