Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

MVC : Models

By
Amareswar rao
you can use tools provided by MVC to construct
the controllers and views for the standard index,
create, edit, and delete scenarios for each of the
model objects. The construction work is called
scaffolding
We call the Artist
property a
navigational
property , because
given an album,
you can navigate to
the album's
associated artist
using the dot
operator
( favoriteAlbum.Art
ist ).
Scaffolding
Scaffolding in ASP.NET MVC can generate the
boilerplate code you need for create, read,
update, and delete (CRUD) functionality in an
application.

The scaffolding knows how to name controllers,


how to name views, what code needs to go in
each component, and where to place all these
pieces in the project for the application to work.

You can also find alternative scaffolding


templates through NuGet
scaffolding templates
Empty Controller

Controller with Empty Read/Write Actions

API Controller with Empty Read/Write Actions

Controller with Read/Write Actions and Views, Using Entity


Framework

Domain-driven design (DDD) is one approach that teams use to


tackle complex applications.

Command-query responsibility segregation (CQRS) is also a pattern


gaining mindshare among teams wrestling with difficult
applications.
Scaffolding - Entity
Framework
EF is an object-relational mapping framework and
understands how to store .NET objects in a relational
database and retrieve those same objects given a LINQ
query.

EF supports a code-first style of development.

Virtual properties are not required, but they do give EF


a hook into your plain C# classes and enable features
like an efficient change tracking mechanism. So that it
might need to issue a SQL UPDATE statement
DbContext Class
When using EF's code-first approach, the gateway to
the database will be a class derived from EF's
DbContext class.

Retrieve all
albums in
alphabetical
order using the
LINQ query

To access a database, all you need


to do is f the data context class.
Controller Class

The code is using the context to load all albums


from the database into a list, and passing the list
as the model for the default view.
Lazy loading vs Eager
loading
The Include method calls that you see in the Index action tell the EF to
use an eager loading strategy in loading an album's associated genre
and artist information.

An eager loading strategy attempts to load all data using a single query.

The alternative (and default) strategy for the EF is a lazy loading


strategy.

With lazy loading, EF loads only the data for the primary object in the
LINQ query (the album), and leaves the Genre and Artist properties
unpopulated:

var albums = db.Albums;


Lazy Loading
Lazy loading brings in the related data on an as-needed basis.

Meaning when something touches the Genre or Artist property of an


Album , EF loads the data by sending an additional query to the
database.

Unfortunately, when dealing with a list of album information, a lazy


loading strategy can force the framework to send an additional query
to the database for each album in the list. For a list of 100 albums, lazy
loading all the artist data requires 101 total queries. The scenario just
described is known as the N + 1 problem (because the framework
executes 101 total queries to bring back 100 populated objects), and is
a common problem to face when using an object-relational mapping
framework. Lazy loading is convenient, but potentially expensive.
Views
@model IEnumerable<MvcMusicStore.Models.Album>
Creating Databases -
Entity Framework
Without a specific connection configured, EF tries to
connect to a LocalDB instance of SQL Server
Express and find a database with the same name as
the DbContext derived class.

If EF can connect to the database server, but doesn't


find a database, the framework creates the database.

The connection string name must match the name


of the data context class. In the code you've been
building,
The EdmMetadata table in the database is a table EF uses to
ensure the model classes are synchronized with the database
schema (by computing a hash from the model class definitions).

If you change your model (by adding a property, removing a


property, or adding a class, for example), EF will either re-create
the database based on your new model, or throw an exception.

Don't worry. EF will not re-create the database without your


permission; you need to provide a database initializer .

Once you remove the EdmMetadata table, you (or your DBA)
will be responsible for making schema changes in the database
to match the changes in your models.
Database Initializers
When you call SetInitializer you need to pass in an
IDatabaseInitializer object,

You can tell EF to re-create the database every time an


application starts. DropCreateDatabaseAlways

You can tell EF to re-create the database only when it


detects a change in the model.
DropCreateDatabaseIfModelChanges
Both initializers require a generic type
parameter, and the parameter must be a
DbContext derived class.

Inside global.asax.cs , you can set an initializer


during application startup.
Migrations - Seeding a
Database
you might want to have a new database populated with some initial
records, like lookup values. You can do this by seeding the database.

you can derive a class from the DropCreateDatabaseAlways class


and override the Seed method.
the new database initializer to work, you need to
change the application startup code to register
the initializer:
the actual amount of work is relatively small and
requires only three steps.

Implement your model classes.

Scaffold your controller and views.

Choose your database initialization strategy.


Editing - Building a
Resource to Edit
The default MVC routing rules deliver the HTTP
GET for Edit action
The HTML sends an HTTP POST request back to
/StoreManager/Edit/8 when the user clicks the
Save button on the page.
The Edit Happy Path

The happy path is the code you execute when


the model is in a valid state and you can save the
object in the database.

An action can check the validity of a model


object by checking the ModelState.IsValid
property.

db.Entry(album).State = EntityState.Modified;
The Edit Sad Path
The sad path is the path the action takes if the
model is invalid.

In the sad path, the controller action needs to re-


create the Edit view so the user can fix the errors
he or she produced.

The process behind the magic is model binding,


and model binding is a central feature of
ASP.NET MVC.
Model Binding
The model binder looks in the request and not in the form
collection.

The model binder uses components known as value providers to


search for values in different areas of a request.

The model binder can look at route data, the query string, and the
form collection, and you can add custom value providers if you so
desire.

The model binder is a bit like a search and rescue dog.

The runtime tells the model binder it wants a value for id , and the
binder goes off and looks everywhere to find a parameter with the
name id .
Model Binding Security

Occasionally there is a property you don't want


(or expect) the model binder to set, and you
need to be careful to avoid an over-posting
attack.

A successful over-posting attack might allow a


malicious person to destroy your application
and your data, so do not take this warning
lightly.
Explicit Model Binding
You can also explicitly invoke model binding using the
UpdateModel and TryUpdateModel methods in your
controller.

UpdateModel will throw an exception if something goes


wrong during model binding and the model is invalid.

TryUpdateModel also invokes model binding, but


doesn't throw an exception. TryUpdateModel does
return a bool a value of true if model binding succeeded
and the model is valid, and a value of false if something
went wrong.
UpdateModel
TryUpdateModel
ModelState
A byproduct of model binding is model state. For
every value the model binder moves into a model,
it records an entry in model state.

You might also like