In todayâ€™s blog post Iâ€™m going to go into more detail about two of the cool new features it brings:
- Built-in support for EF 4.1 (which includes the new EF â€œcode-firstâ€ support)
- Built-in data scaffolding support within Visual Studio (which enables you to rapidly create data-driven sites)
These two features provide a really sweet, and extremely powerful, way to work with data and build data-driven web applications.
Scenario Weâ€™ll Build
To help illustrate how to use the above features, weâ€™ll walkthrough building a simple data-drive site. It will support listing products:
As well as creating/editing new products (and categories):
We can now build this entire application (and create the database that backs it) with ASP.NET MVC 3 in only a minute or two.
Step 1: Create New Project
Weâ€™ll begin by creating a new ASP.NET MVC 3 project (using the File->New Project menu command). Weâ€™ll use the â€œInternet Projectâ€ template â€“ which will provide us with a default starter template for our application.
When you look at the newly created project within the Solution Explorer, youâ€™ll see that the ASP.NET MVC 3 Tools update adds a new assembly â€“ EntityFramework â€“ to our ASP.NET MVC 3 projects:
The EntityFramework assembly implements Entity Framework 4.1 â€“ which we also released last month. EF 4.1 brings with it a bunch of great data API improvements to .NET â€“ including the new â€œcode firstâ€ option. EF Code First provides a really elegant and clean way to work with data, and enables you to do so without requiring a designer or XML mapping file. You can now easily take advantage of this by default with all new ASP.NET MVC 3 projects.
Weâ€™ll be using the EF Code First approach to implement our data access for this application.
Step 2: Implement Model Classes
Our first step will be to create two classes â€“ Product and Category â€“ that weâ€™ll use to define the â€œmodelâ€ of our application. Weâ€™ll implement these as standard â€œplain old C# objectsâ€ within the \Models folder of our project using the code below:
Notice how the above classes are just standard classes with .NET data-types. They do not need to derive from any base class, nor implement any interfaces.
In addition to standard scalar properties, each class has an â€œassociationâ€ property. For example, the â€œProductâ€ class has a â€œCategoryâ€ property that enables a developer to get access to the Category it belongs to. Likewise the â€œCategoryâ€ class has a â€œProductsâ€ property that enables a developer to retrieve the Products that are within that particular Category. EF Code First can handle automatically managing these associations (using the Primary Key/Foreign Key values), and can lazy load the appropriate data on-demand.
Step 3: Implement a StoreContext Class using EF Code First
Now that weâ€™ve defined our two model classes, our next step will be to implement a â€œDbContextâ€ class using EF code First that will map the model classes to tables in a database. Weâ€™ll implement this using the code below:
The â€œStoreContextâ€ class above is the DbContext class we are using to map our Product and Category classes to/from a database. It derives from the DbContext base class provided by EF Code First, and exposes two properties that correspond to tables within our database. For this sample we are using the default â€œconvention over configurationâ€ based mapping rules to define how the classes should map to/from the database. This means that the Products property will map to a Products table, and the Categories property will map to a Categories table. In later blog posts Iâ€™ll talk about how you can optionally override this and perform custom mappings.
You can add the above class anywhere within your solution. For example, you could add it within the \Models folder of your project â€“ or within a separate class library project if you prefer to keep your data code separate. Youâ€™ll want to add a â€œusingâ€ statement to the System.Data.Entity namespace at the top of the class file (in order to reference the DbContext and DbSet<T> classes).
Step 4: Scaffold a Categories Controller
We have everything we need to model our data and save/retrieve it from a database. Now letâ€™s create an ASP.NET MVC Controller class that will implement the support necessary to display our Category data and enable creating/editing/deleting Category objects. Prior to last monthâ€™s ASP.NET MVC 3 Tools Update, you would have had to manually write a Controller class to do this (and implement all of the EF data access code yourself). The ASP.NET MVC 3 Tools Update now includes built-in â€œscaffoldingâ€ support that can help do this for you automatically.
To scaffold a new Categories controller class, weâ€™ll right-click on the â€œ/Controllersâ€ folder of our project and choose the Add->Controller context menu:
Selecting Add->Controller will bring up the â€œAdd Controllerâ€ dialog. Weâ€™ll name the controller class we want to create â€œCategoriesControllerâ€. Starting with last monthâ€™s ASP.NET MVC 3 Tools Update, the â€œAdd Controllerâ€ dialog also now supports a new â€œScaffolding optionsâ€ section â€“ which enables you to choose to â€œscaffoldâ€ the new controller using a variety of built-in templates:
Weâ€™ll choose the â€œController with read/write actions and views, using Entity Frameworkâ€ template â€“ which will create a Controller class that has all of the EF code necessary to create, update, list and delete model objects.
After selecting this template, we can choose the model class we want our Controller to implement CRUD support for â€“ in this case the â€œCategoryâ€ class. We can also select the EF DbContext/ObjectContext class that we want to use to access the database â€“ in this case the â€œStoreContextâ€ class we defined earlier:
When we click the â€œAddâ€ button, Visual Studio will automatically create a CategoriesController class for us â€“ with appropriate Create, Edit, Details, Delete and Index action methods inside it â€“ as well associated view templates for each of the actions:
If you open the CategoriesController.cs class youâ€™ll find that the action methods within it implement the EF data access code necessary for CRUD support:
And now we have all of the code we need to implement data listing/editing for Categories within our database
Step 5: Configuring our Database Location
The last step weâ€™ll do before running our application is to point our application at the database we want to use. EF code first allows you to use an existing database you already have defined, or alternatively you can point it at a database that doesnâ€™t yet exist â€“ in which case it will automatically create it for you using the model classes youâ€™ve defined.
By default, you actually donâ€™t need to configure a connection-string to point at a database. If you donâ€™t specify one, EF Code-First will by default create a new SQL Express database whose name matches your DbContext class name (for example: above it would create a ScaffoldingDemo.Models.StoreContext database within your local .\SQLExpress database instance).
Explicitly Specifying a Connection-String
You can alternatively explicitly specify where you want your database to live by adding a connection-string to your applicationâ€™s web.config file. Youâ€™ll want the name of the connection-string to match the DbContext class name. For example â€“ in our application above our DbContext class was named â€œStoreContextâ€, and so by default EF will look for a connection-string with the same name to determine the database location.
Below is the entry weâ€™d add to our web.config file if we wanted to use an embedded SQL CE database named â€œStore.sdfâ€ within our applicationâ€™s \App_data folder:
You can learn more about SQL CE â€“ and the new VS 2010 SP1 tooling support for it â€“ from my previous blog post about it.
Step 6: Run the Application
Ok â€“ letâ€™s now run the application and navigate to the /Categories URL. This will execute our CategoriesControllerâ€™s Index() method â€“ which will list all categories in our database. Currently we donâ€™t have any:
Letâ€™s click the â€œCreate Newâ€ link to create a new category â€“ this will navigate to the /Categories/Create URL, which provides us with a form to create a new category:
Clicking the â€œCreateâ€ button will post the form to our CategoriesController and add a new Category to our database. We can repeat this a few times to add several different categories:
The cool thing is that we didnâ€™t have to write any Controller or View code to enable this â€“ the scaffolding support automatically generated the code we needed to enable this. This provides a really easy way to get started. We can then go in and tweak it as necessary to customize the functionality further.
Step 7: Looking at the database
We configured our application to use a connection-string that pointed to a SQL CE database that (at the time) didnâ€™t exist. When we ran our application, EF 4.1 detected that the database didnâ€™t exist and automatically created it for us â€“ based on the Product and Category classes we defined earlier.
To see the database, click the â€œShow All Filesâ€ icon at the top of Visual Studioâ€™s â€œSolution Explorerâ€ and add the â€œStore.sdfâ€ database that was automatically created by EF to your project:
You can then double-click the database to open it up in the Server Explorer â€“ and expand the tables within it to see the schema that was created:
Notice above how EF Code First automatically created the appropriate database schema based on the Category and Product classes we created earlier. It also automatically setup Primary Key/Foreign-Key relationships between the two tables based on the association properties specified in the classes.
Step 8: Scaffolding a Products Controller
Weâ€™ve created a CategoriesController class to manage listing and editing Categories. Letâ€™s now create a ProductsController class to manage listing and editing Products.
Just like before, weâ€™ll right-click on the \Controllers folder in our project and choose the Add->Controller context menu. Weâ€™ll name the Controller class we want to create â€œProductsControllerâ€ and indicate that we want to scaffold using the EF template with a Product model class:
Clicking the â€œAddâ€ button will scaffold a ProductsController class for us, with appropriate action methods for CRUD scenarios, and create the associated view templates that go with them:
We can then run our project again and navigate to the /Products URL within it:
Letâ€™s click the â€œCreate Newâ€ link to create a new Product:
One cool thing to notice is that the â€œCategoryâ€ is a drop-down of valid Categories (and not just a textbox with a foreign-key integer value):
The scaffolding support within Visual Studio was smart enough to detect that Category was an association, and scaffold EF code that populates the drop-down with valid Categories.
After entering several products our /Products URL will display the data like below:
Notice again how Category is displayed using the friendly name â€“ and not just the foreign-key value.
The above walkthrough provided a quick look at the new EF code-first and data scaffolding support built-into the ASP.NET MVC 3 Tools Update, and how you can use them to easily and quickly jumpstart application development. EF Code First enables you to write incredibly clean data access code. The data scaffolding support enables you to rapidly create data UI â€“ and then allows you to go in and easily tweak/customize it further.
In addition to working with EF Code-First, you can also use the data scaffolding support against standard EF ObjectContext objects (built using either the database-first or model-first approach and the EF WYSIWYG designer).
You can learn more about the new ASP.NET MVC 3 Scaffolding Support from Steve Sandersonâ€™s excellent talk about it at MIX:
- Scaffolding â€“ ASP.NET, NuGet, MVCScaffolding â€“ Steve Sanderonâ€™s MIX talk about it
In his talk Steve also covers how you can use the scaffolding support from the command-line (using NuGet) as well as how you can download and use additional scaffolding templates (for example: ones that can automatically implement a repository pattern, etc). Also make sure you bookmark Steveâ€™s excellent blog series about scaffolding (and its extensibility) here:
- Scaffolding with ASP.NET MVC 3 â€“ Excellent blog series about ASP.NET MVC 3 Scaffolding
EF Code First
Iâ€™ll be doing more blog posts about EF Code First in the future. Below are links to some tutorials Iâ€™ve written in the past about it:
- Code First Development with Entity Framework 4.x
- EF Code First: Custom Database Schema Mapping
- Using EF Code First with an Existing Database
Note: The above tutorials were written against the CTP4 release of EF Code First (and so some APIs are a little different) â€“ but the concepts and scenarios outlined in them are the same as with the final release.
ASP.NET MVC 3
If you want to learn more about ASP.NET MVC 3, I highly recommend Scott Hanselmanâ€™s excellent video presentations at the Dutch DevDays and at MIX:
- ASP.NET MVC 3 101 â€“ From Beginning to Advanced
- Overview of the MS Web Stack of Love â€“ Scottâ€™s talk at MIX
Also check out all of the new content and videos on the http://asp.net/mvc web-site:
The new ASP.NET MVC 3 Tooling Update is full of goodness. If you havenâ€™t already downloaded and installed it I highly recommend you do so. Stay tuned for even more blog posts about it!
Hope this helps,
P.S. I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu
(We sincerely thank above Site and the Author. If you are the owner of the content and do not want to distribute your content to our website, please contact us we will surely remove the content.)