For full documentation please visit: http://www.asp.net/mvc/overview/getting-started
ASP.NET MVC encourages you to specify functionality or behavior only once, and then have it be reflected everywhere in an application. This reduces the amount of code you need to write and makes the code you do write less error prone and easier to maintain.
You don’t actually have to specify which database to use, Entity Framework will default to using LocalDB. In this section we’ll explicitly add a connection string in the Web.config file of the application.
LocalDB is a lightweight version of the SQL Server Express Database Engine that starts on demand and runs in user mode. LocalDB runs in a special execution mode of SQL Server Express that enables you to work with databases as .mdf files. Typically, LocalDB database files are kept in the App_Data folder of a web project.
SQL Server Express is not recommended for use in production web applications. LocalDB in particular should not be used for production with a web application because it is not designed to work with IIS. However, a LocalDB database can be easily migrated to SQL Server or SQL Azure.
If you don’t specify a connection string, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class.
The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a view.
By including a @model statement at the top of the view template file, you can specify the type of object that the view expects.
Models and data annotations:
Data Annotations explained:
HttpPost attribute specifies that that overload of the Edit method can be invoked only for POST requests. You could apply the HttpGet attribute to the first edit method, but that’s not necessary because it’s the default. The Bind attribute is another important security mechanism that keeps hackers from over-posting data to your model. You should only include properties in the bind attribute that you want to change.
The ValidateAntiForgeryToken attribute is used to prevent forgery of a request and is paired up with @Html.AntiForgeryToken() :
Avoiding cross site request forgery attacks
Modifying data in a GET method also violates HTTP best practices and the architectural REST pattern, which specifies that GET requests should not change the state of your application. In other words, performing a GET operation should be a safe operation that has no side effects and doesn’t modify your persisted data.
To force your computer to use US English, you can add the globalization element to the projects root web.config file. The following code shows the globalization element with the culture set to United States English.
By default, when you use Entity Framework Code First to automatically create a database, Code First adds a table to the database to help track whether the schema of the database is in sync with the model classes it was generated from. If they aren’t in sync, the Entity Framework throws an error. This makes it easier to track down issues at development time that you might otherwise only find (by obscure errors) at run time.
The AddOrUpdate method in the following code performs an “upsert” operation:
When there is a model change in your code-base (like adding a new property) database schema and entity framework models should match. Otherwise run-time will throw errors. There are a few approaches to resolving the error:
- Have the Entity Framework automatically drop and re-create the database based on the new model class schema. This approach is very convenient early in the development cycle when you are doing active development on a test database; it allows you to quickly evolve the model and database schema together. The downside, though, is that you lose existing data in the database — so you don’t want to use this approach on a production database! Using an initializer to automatically seed a database with test data is often a productive way to develop an application.
- Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script.
- Use Code First Migrations to update the database schema.
The validation support provided by ASP.NET MVC and Entity Framework Code First is a great example of the DRY principle in action. You can declaratively specify validation rules in one place (in the model class) and the rules are enforced everywhere in the application.
ValudationMessageFor (single error per place)
ValidationSummary usage (multiple errors in one place)
Post/Delete Sample (ActionName(“Delete”):
Another common way to avoid a problem with methods that have identical names and signatures is to artificially change the signature of the POST method to include an unused parameter. For example, some developers add a parameter type FormCollection that is passed to the POST method, and then simply don’t use the parameter:
In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.
Entity Set => Table
Entity => Row
To tell Entity Framework to use your initializer class, add an element to the entityFramework element in the application Web.config file (the one in the root project folder), as shown in the following example:
As an alternative to setting the initializer in the Web.config file is to do it in code by adding a Database.SetInitializer statement to the Application_Start method in in the Global.asax.cs file.
Create Page Example:
It’s a security best practice to use the Include parameter with the Bind attribute to white list fields. It’s also possible to use the Exclude parameter to blacklist fields you want to exclude. The reason Include is more secure is that when you add a new property to the entity, the new field is not automatically protected by an Exclude list.
A production quality application would log the exception.
An alternative way to prevent over posting that is preferred by many developers is to use view models rather than entity classes with model binding. Include only the properties you want to update in the view model. Once the MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such as AutoMapper. Use db.Entry on the entity instance to set its state to Unchanged, and then set Property(“PropertyName”).IsModified to true on each entity property that is included in the view model. This method works in both edit and create scenarios.
What is the use of C# Automapper ?
Using AutoMapper with ASP.NET MVC Views
This is server-side validation that you get by default
Sample Edit Example:
These changes implement a security best practice to prevent over posting. Bind attribute clears out any pre-existing data in fields not listed in the Include parameter.
When the SaveChanges method is called, the Modified flag causes the Entity Framework to create SQL statements to update the database row. Concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn’t change. If you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified.
As a best practice to prevent over posting, the fields that you want to be updateable by the Edit page are white listed in the TryUpdateModel parameters. Currently there are no extra fields that you’re protecting, but listing the fields that you want the model binder to bind ensures that if you add fields to the data model in the future, they’re automatically protected until you explicitly add them here.
Difference between updatemodel and tryupdatemodel
Remote validation in mvc
The DbContext that reads an entity is disposed after a page is rendered. When the HttpPost Edit action method is called, a new request is made and you have a new instance of the DbContext, so you have to manually set the entity state to Modified. Then when you call SaveChanges, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed.
If you want the SQL Update statement to update only the fields that the user actually changed, you can save the original values in some way (such as hidden fields) so that they are available when the HttpPost Edit method is called.
Deleting an Entity:
This code instantiates a Student entity using only the primary key value and then sets the entity state to Deleted. That’s all that the Entity Framework needs in order to delete the entity.
Insert, Update and Delete using Entity Framework:
In this video, Julie Lerman uses Visual Studio 2010 to show you how Entity Framework automatically creates insert, update, and delete commands based on changes to your entities and sends them to the database.