Create an ASP.NET Dynamic Data Website Using ADO.NET Entity Framework

Posted by: Suprotim Agarwal , on 11/20/2008, in Category ASP.NET
Views: 154850
Abstract: 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.
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:
I assume you have Microsoft Visual Studio 2008 with Service Pack 1 or Visual Web Developer 2008 Express Edition with Service Pack 1 installed. Without it, you will not be able to build Dynamic Data Websites.
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
Templates.jpg
The structure of the application in the Solution Explorer will look similar to the following:
DynDataProjectStructure.jpg
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:
ServerConnection.jpg
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)
AddEntityModel.jpg
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:
DataModelWizard Step1.jpg
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.
DataModelWizard Step2.jpg
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.
DataModelWizard Step3.jpg
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.
DDTables.jpg
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.
DDTableDetails.jpg
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:
DDChildTables.jpg
However if you click on this link (View Order_Details), a strange error appears.
DDError.jpg
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.
DDOrderDetails.jpg
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. 
 If you liked the article,  Subscribe to my RSS Feed.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

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!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
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 ten consecutive times. 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



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Milos on Monday, November 24, 2008 4:07 AM
Great article.
Comment posted by abdullah on Tuesday, November 25, 2008 6:13 AM
test
Comment posted by piyush varma on Sunday, December 14, 2008 1:29 AM
How to refresh the data model when the database is modified?
Comment posted by Nandagopal on Tuesday, December 30, 2008 8:01 PM
Hi,
I tried exactly whatever said in this article, I am able to see the default.aspx page with the list of tables but if I click on any the table I am getting the following error

The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.
Comment posted by Thanigainathan on Wednesday, December 31, 2008 11:13 PM
Hi,

Microsoft has recently released a fix to the Entity Framework with Dynamic Data web applciations.

http://www.microsoft.com/downloads/details.aspx?familyid=B9DE7937-2C12-4F16-AD66-A31B83931953&amp;displaylang=en&displaylang=en

you can use this for solving that problem.

Can you please tell how to remove the unwanted fields that got generated.

Thanks & regards,
Thani
Comment posted by Suprotim Agarwal on Thursday, January 1, 2009 11:17 AM
Thanks Thanigainathan for that link. Please elaborate more on the unwanted fields.
Comment posted by Nikunj on Friday, January 2, 2009 9:30 AM
How do we go about deciding if a project or precisely web application can be designed with Dynamic Data WebSites?

And how far can ve customize Dynamic Data Web Sites ?
Comment posted by Kalyan on Monday, May 18, 2009 6:15 PM
Well explained. The basics about Dynamic Data using scaffolding can be found here
http://www.techbubbles.com/aspnet/creating-a-dynamic-data-web-site-using-scaffolding/
Comment posted by Khan on Thursday, June 18, 2009 2:48 PM
Thanks for the article it really helps. I have one problem I cannot see all tables of my database in the dynamic website. I can see only four tables. how do I enable all tables and views in the website, which I see in server explorer.
Comment posted by mostafa on Saturday, July 4, 2009 4:08 AM
A very good explanation
thanks a lot!!!

Comment posted by sahil31_mohali on Wednesday, August 5, 2009 6:46 AM
nice article
Comment posted by hospice home care on Tuesday, August 25, 2009 3:21 PM
Dear web-master ! I looked your site and I want to say that yor very well
made it .All information on this site is represented for users. A site is
made professionally. So to hold
http://web.zone.ee/aceba/hospiceh43/index.html
<a href=http://web.zone.ee/aceba/hospiceh43/index.html> hospice home care </a>
Comment posted by Basanth on Tuesday, October 20, 2009 5:28 AM
Please help me.

Please read my question carefully and reply me.

I have two tables as table1 and table2.

In table1 i have columns as AddressID(Primary Key),Address1,Address2,City

In table2 i have columns as ContactID(Primary Key),AddressID(Foriegn Key),Last Name,First Name.

By using join operation i can retrive data from both the tables.

I created a Model in my MVC Application.I can see both the tables in enitity editor.

In the ViewData folder of my solution explorer i created two class as ContactViewData.cs and SLXRepository.cs

In the ContactViewData.cs i have following code

public IEnumerable<CONTACT> contacts
        {
            get;
            set;
        }

In the SLXRepository.cs i have following code

public  IEnumerable<CONTACT> GetContacts()
        {
            var  contact = (from c in context.CONTACT
                                                  join a
                                                    in context.ADDRESS on c.ADDRESSID equals a.ADDRESSID
                                                  select new
                                                   {
                                                       a.ADDRESS1,
                                                       a.ADDRESS2,
                                                       a.CITY,
                                                       c.FIRSTNAME,
                                                       c.LASTNAME
                                                   });

           return contact;

        }



I am getting the error in return type Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<SiennaSLX.Models.CONTACT>'. An explicit conversion exists (are you missing a cast?)
Comment posted by Vishnukumar SR on Friday, November 27, 2009 6:25 AM
Hi Frnds,
In This Aricle Itz published the screen shot as like soo many options in the Installed templates  such as dynamic data website,dynamic entities website,etc and so on...
My problem is i cant findout this options in my machine.suppose Is this option avilable in express edtion ?
i have installed crack file edtion[serial number]...
Give me Suggesion

by
Vishnukumar SR
Comment posted by Reena on Wednesday, January 6, 2010 10:54 PM
hi
my Question is how to website golobally declare on any computer means my website put on google how to put it on google?
Comment posted by mordhwaj jaiswal on Tuesday, October 5, 2010 4:16 AM
Thanks information
how to use entity data model in ado.net
Comment posted by mbourgon on Tuesday, February 15, 2011 4:29 PM
Excellent article, thanks.  I've been looking for something to easily generate a front-end, and this works for what I'm trying to do!
Comment posted by william on Thursday, May 26, 2011 1:35 AM
i have created one site by using one table.
however i dont want to show its primary key on front end as i am inserting it by identity property of table.
how to do this??
Comment posted by william on Thursday, May 26, 2011 2:39 AM
i have created one site by using one table.
however i dont want to show its primary key on front end as i am inserting it by identity property of table.
how to do this??
Comment posted by joyfulkris on Tuesday, October 4, 2011 9:01 AM
Have two .edmx files. Used to pull to 3 table from one and 2 table from other. This has to be shown up in different pages but see all the tables been pulling up... Could any one please provide a solution for this..
Comment posted by srinivas on Saturday, July 28, 2012 2:03 AM
Thanks For your Support..!!!!
Comment posted by Ramesh on Friday, September 14, 2012 2:23 AM
Stuck with error: The context type 'Hello.MyDbEntities' is not supported
Comment posted by tewelde on Monday, December 31, 2012 12:08 PM
oh this site very slow to use? not to open just it is difficult to use the links above please update some extension in order to use the clients fast.
Comment posted by dip on Monday, January 6, 2014 6:20 AM
I like ur Articel but whenever Right-click Default.aspx > View in Browser then not displays the tables in browser......

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

C# .NET BOOK

C# Book for Building Concepts and Interviews

Tags

JQUERY COOKBOOK

jQuery CookBook