So couple of days ago I talked about the new ADO.NET Entity Data Model. The Entity Data Model sometimes also referred to as the Entity Framework can also be used with the new Scaffolding feature that’s available in .NET 3.5 SP1. Scaffolding allows the run-time engine to build a CRUD (Create, Read, Update, Delete) operation system for a given model. However, it is often times useful to include a model just for viewing purposes not for editing or deleting – which is a behavior that comes in by default with the scaffold operation. In order to to that you can simply edit the Global.asax file and before the default routing code add the following lines of code:
#region Readonly tables
var visibleTables = from t in MetaModel.Default.Tables
where t.Scaffold == true
select t;
var readOnlyTables = new StringBuilder();
foreach( var table in visibleTables ) {
var isReadOnly = table.Attributes.OfType<ReadOnlyAttribute>().
DefaultIfEmpty( new ReadOnlyAttribute( false ) ).
FirstOrDefault();
if( isReadOnly.IsReadOnly )
readOnlyTables.Append( table.Name + "|" );
}
routes.Add( new DynamicDataRoute( "{table}/{action}.aspx" ) {
Constraints = new RouteValueDictionary( new
{
action = "Edit|Insert",
table = readOnlyTables.ToString().Substring( 0, readOnlyTables.Length - 1 )
} ),
ViewName = "Details",
Model = model
} );
#endregion
Basically using LINQ this code goes through all the tables in the MetaModel (which holds all the models in a given namespace) and looks for the [ReadOnly(true)] attribute for each of the classes. If there’s a table found with the ReadOnly attribute the Edit/Delete operation is re-routed to the View Page (Routing is also a new technique that’s available in .NET 3.5 SP1).
Some excerpts of this code taken from Stephen Naughton’s blog.