Create an ASP.NET Dynamic Data Website Using ADO.NET Entity Framework
This article will demonstrate how to create an ASP.NET application that uses ASP.NET Dynamic Data framework. Dynamic Data provides a scaffolding framework that enables you to create a data-driven application within minutes using either the LINQ to SQL or Entity Framework data model. Scaffolding is a mechanism that enables ASP.NET to analyze your data model and dynamically generate pages based on the data model. These generated Web pages provide full capabilities to display, insert, delete, and edit data. We will be using the Northwind database to build an application that displays pages of data.
Requirements:
Step 1: Open Visual Studio 2008 > Go to File menu > New Web Site. Under the installed templates, select ‘Dynamic Data Entities Web Site’. We have selected this template since we wish to use the ADO.NET Entity Framework. Enter the Name and Location of the Web site > Select the Language (C# or VB) of your choice and click OK
The structure of the application in the Solution Explorer will look similar to the following:
Step 2: The next step is to add a data source to the project. I am using SQL Server 2005 Enterprise Edition. Go to your ‘Server Explorer’ > Right Click ‘Data Connections’ > Add Connection. I chose the ‘Server Name’ as (local) and ‘Database’ as ‘Northwind’. The connection appears in the ‘Solution Explorer’ as shown below:
Note: If you are using SQL Express, follow these steps. Assuming you have a App_Data folder in Solution Explorer > Right-click the App_Data folder > Add Existing Item. Enter the location where you installed the Northwind database file. The path on my machine is C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\AdventureWorks_Data.mdf
Step 3: The next step is to create a Data Model. Right-click the Project > Add ASP.NET Folder > App_Code. Right-click the App_Code folder > Add New Item. In the Visual Studio installed templates, select 'ADO.NET Entity Data Model' > Enter a name for the database model (NorthwindModel.edmx)
When you click Add, Visual Studio asks if you want to place the file in an ASP.NET_Code folder. Choose Yes. The Entity Data Model Wizard starts up as shown below:
Click ‘Generate from database’ to specify that you want to generate the model from a database. The next step is to ‘Choose your DataConnection’. Select the ‘Northwind’ connection that you had created. Also remember to check the ‘Save entity connection settings in Web.config’ checkbox.
Note: SQL Express users can select Northwind_Data.mdf from the list.
Click Next. In the 'Choose your Data Objects' screen, select 'Tables' to select all tables from the database. The model namespace is 'NorthwindModel' as shown below. Click Finish.
Step 4: The next step is to register the data model in the Global.asax for the Dynamic Data to use. Add the following namespace <%@ Import Namespace="NorthwindModel" %> and the following line to the Global.asax:
C#
MetaModel model = new MetaModel();
model.RegisterContext(typeof(NorthwindEntities), new ContextConfiguration() { ScaffoldAllTables = true });
VB.NET
Dim model As New MetaModel()
model.RegisterContext(GetType(NorthwindEntities), New ContextConfiguration() With {.ScaffoldAllTables = True})
The code shown above registers the Entity Framework data context and enables scaffolding of the data model.
You can now test the application you have built. Right-click Default.aspx > View in Browser. You will see a page that displays a list of tables that you added to the data model.
Click on a table say ‘Orders’ . A page gets displayed with the Order table details. The table contains fully functional links to edit, delete and select data. You can navigate through the records as well as add new items by clicking the Insert new item button at the bottom of the page. Check these functionality out. It's amazing to see how these pages are dynamically created with the help of a few templates.
Now if the table has a parent-child relationship with another table (in our case let us take the example of Orders and OrderDetails), then a link is provided (View Order_Details) to view details of the child table as shown below:
However if you click on this link (View Order_Details), a strange error appears.
The error says “A property with name 'Orders.OrderID' does not exist in metadata for entity type 'NorthwindModel.Order_Details'”
That’s a bug in the RTM release of Dynamic Data. The Dynamic Data has trouble with some data relationships in Entity Framework data models. More info about it can be found over here.
Fix to the Bug: The fix to this bug was provided by scothu. The fix is to replace the default Entity Framework Data Model provider with a new data model provider. You can download the fix (DynamicDataEntityFrameworkWorkaround.zip ) from here.
Step 5: Once you have downloaded the .zip file, extract it. Then right-click Website > Add ASP.NET Folder > Bin > Right-click Bin > Browse to Microsoft.Web.DynamicData.EFProvider.dll and add it to the Bin folder. Now for the fix to work, we need to make some changes in the Entity Framework Model in Global.asax.
Now replace this line:
model.RegisterContext(typeof(NorthwindEntities), new ContextConfiguration() { ScaffoldAllTables = true });
with this line
C#
model.RegisterContext(new Microsoft.Web.DynamicData.EFDataModelProvider(typeof(NorthwindEntities)),
new ContextConfiguration() { ScaffoldAllTables = true });
VB.NET
model.RegisterContext(New Microsoft.Web.DynamicData.EFDataModelProvider(GetType(NorthwindEntities)), New ContextConfiguration() With {.ScaffoldAllTables = True})
We also need to change the GetDisplayString () in the ForeignKey.ascx and add a try-catch block to it. Open the DynamicData\FieldTemplates\ForeignKey.ascx.cs or vb and replace the GetDisplayString method shown below:
C#
protected string GetDisplayString() {
return FormatFieldValue(ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue));
}
VB.NET
Protected Function GetDisplayString() As String
Return FormatFieldValue(ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue))
End Function
with this method shown below to add the try-catch block. Note we are returning the ForeignKeyColumn.ParentTable.DisplayName in the catch block when an exception is thrown
C#
protected string GetDisplayString()
{
try
{
return FormatFieldValue(ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue));
}
catch (Exception)
{
return ForeignKeyColumn.ParentTable.DisplayName;
}
}
VB.NET
Protected Function GetDisplayString() As String
Try
Return FormatFieldValue(ForeignKeyColumn.ParentTable.GetDisplayString(FieldValue))
Catch e1 As Exception
Return ForeignKeyColumn.ParentTable.DisplayName
End Try
End Function
Now build and preview the Default.aspx again. Click the Orders table and then click on View Order_Details link. You will now be able to view the OrderDetails for that Order.
In this article, we explored how to effortlessly create a fully functional ASP.NET Dynamic Data Web site without writing much code. In the forthcoming articles, we will explore how to extend the default behavior of Dynamic Data. Stay Tuned! I hope you liked my article and I thank you for viewing it.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn