How to control tables and columns in ASP.NET Dynamic Data?
Posted: (EET/GMT+2)
Are you already using .NET 3.5 SP1? If yes, then you can utilize a very nice technique for "webifying" databases, called ASP.NET Dynamic Data. If you are not yet familiar with this new technology, MSDN has an introduction for you.
If you start your first Dynamic Data project in Visual Studio 2008, and immediately run the generated application, you will unfortunately see an error message. This is because you haven't yet specified the data source you want. If you are using SQL Server, LINQ To SQL is my choice, and so you need to edit the Global.asax.cs file and follow the instructions in the code comments.
But once you are done specifying your data context, how do you continue from there? For example, you might want to specify which tables are visible, and which aren't. Easy. Just create a class named the same as the generated class name for your database table (for example, "Order"), and then associate the attribute ScaffoldTable with it:
using System.ComponentModel.DataAnnotations;
...
[ScaffoldTable(true)]
public partial class Order { }
Here, the ScaffoldTable attribute (from the System.ComponentModel.DataAnnotations namespace) indicated to the Dynamic Data system that the table should be visible. Note that since your class is a partial class, it actually doesn't make much difference where you put the declaration. For instance, a code file like "TableContol.cs" would be a good idea.
You can also control things at the column level, which is often just what you need. However specifying column-based settings is somewhat more tricky because you cannot define "partial properties" in C#, at least just yet. Thus, the option is to create a so-called metadata class for your table class, and associate these two together with the MetadataType attribute like this:
[MetadataType(typeof(MyOrderMetadata))]
public partial class Order { }
public class MyOrderMetadata
{
[ScaffoldColumn(false)]
public object OrderDate;
}
With this metadata class in place, it is easy to start defining even more attributes to the columns. Such attributes include ScaffoldColumn, DisplayFormat and UIHint.
For example:
[DisplayFormat(DataFormatString="{0:dd.MM.yyyy}")]
public object OrderDate;
Good luck with ASP.NET Dynamic Data.