Wednesday, May 25, 2011

ASP.NET Dynamic Data - Part 2 - Create a Web Site From Scratch

Part 1 in the serie about ASP.NET Dynamic Data gave a very quick overview over the Dynamic Data framework. Now how do you create a Dynamic Data Web Site from scratch using in built-in scaffolding support?

Create the Web Site

It's very easy to create a Dynamic Data Web Site from scratch. In Visual Studio just choose File -> New -> Web Site -> ASP.NET Dynamic Data Entities.
Dynamic Data can of course also be create using Linq to SQL, and as a Web Application.
The structure of the project looks like this

Create and use the DataContext

Next the DataContext used to scaffold the database should be created. If you don't know how to create the entity model, see the How to: Create a New .edmx File (Entity Data Model Tools) from MSDN.
To use the generated open the Global.asax file, and find the line on the picture below, the line should be uncommented and YourDataContext should be changed to the name of you own DataContext, in my case the context in DatabaseEntities.
The line also allows you to control if all tables should be scaffoleded, the default is not to scaffold all tables. In my case I could scaffold all tables, but for the sake for this tutorial, I'll defined which tables to scaffold using partial classes.

Choose the tables to scaffold

My database consists of two tables named Products and Categories, the entity classes have the same name, this means that my two partial classes looks like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DatabaseModel;
using System.ComponentModel.DataAnnotations;

namespace DatabaseModel
{
    [ScaffoldTable(true)]
    public partial class Products
    {
    }

    [ScaffoldTable(true)]
    public partial class Categories
    {
    }
}
The ScaffoldTable attribute indicates that the table should be scaffolded. Remember to place the partial classes in the same namespace as the original entity classes, otherwise this won't work.

Test the site

You can know publish the Web Site, are it is now possible to view, edit, create and delete data from the database. This is how easy Dynamic Data allows you to create a basic web interface to you database.
It the next part of this serie, I'll show you how to customize the default field templates.

No comments:

Post a Comment