Building A Razor Web Pages Site With Database First And Entity Framework

Since I published an item covering Code First development with Entity Framework and WebMatrix, I have had a few requests to provide a guide to working with the Entity Framework from a database first point of view. This post answers those requests and provides a step by step guide to getting up and running with a WebMatrix web site based on the Northwind sample database that comes with SQL Server CE 4.0.

Entity Framework (EF) is a technology that attempts to alleviate the friction caused when developers have to move between the conceptual representation of their application (the entities that represent the application's domain) and the logical or relational representation of the data (typically the database itself). On the one hand, a developer will work with their entities, such as Products or Employees using C# to instantiate them, bind them to grids, change them and so on. On the other hand, the developer will use another language (SQL) to persist entities to a data store (the database), or to retrieve them from persistent storage. EF's role is to map entities to database schema (tables, views etc) and to allow the developer to stick to C# alone - letting EF take care of transitioning C# Linq expressions to SQL to be executed against the database. EF does more than that. It is also a code and database generation tool. In the previous article, EF generated a database, including all tables, relationships etc, based purely on the defintion of some C# classes. In this article, EF will generate class definitions and mappings based purely on the schema of an existing database.

It is possible to generate the various files that EF needs by using a command line tool - edmgen.exe. However, this article looks at the wizard and design tools that are freely available for this task instead. The EF wizard comes as a standard part of both Visual Studio 2010 and Visual Web Developer Express 2010 (VWD). It is not available in WebMatrix 1.0 and there are no indications at the moment that it will be added to WebMatrix in version 2.0 - the Beta of which is available now. So, that leaves VWD as the remaining free option. If you already have VWD installed, you must make sure that you also have Service Pack 1 as this contains the tooling for generating Razor Web Pages sites. If you download VWD, you automatically get SP1 anyway.

Once you have started VWD, choose New Web Site, and then select ASP.NET Web Site (Razor) from the options available

This generates a site based on the Starter Site template. You can remove the Account folder if you like, as well as the StarterSite.mdf file in App_Data

If you remove the database file, you must also comment out or delete the first line in _AppStart.cshtml

Now you need a database. Right click on the App_Data folder in Solution Explorer and choose Add Existing Item.

Navigate to the location of Northwind.sdf. This is typically C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Samples. (x86) will only feature in the file path on 64 bit operating systems, so if you are working with 32 bits, leave that part out. If you cannot find a copy of Northwind.sdf on your system, download this sample from one of my previous articles and borrow the copy from the App_Data folder there. Once you have organised a copy of the database, you are ready to start the EF wizard.

Right click in the Solution Explorer and choose Add New Item. From the options available, select ADO.NET Entity Data Model and name it Northwind.edmx.

You will receive a warning that special files such as those that comprise and ADO.NET Entity Data Model should go in an App_Code folder. Click Yes.

Select Generate From Database when you are prompted to choose the content source for your Model

Click Next and choose New Connection. Select Microsoft SQL Server Compact 4.0 as the Data Source, then browse to the Northwind.sdf file that you have in your App_Data folder

Select that so that the connection string is generated and leave the name of the connection string as NorthwindEntities.

Click Next so that you are taken to the dialog shown below where you specify the objects to be used in the Model. Choose Tables and leave the Model Namespace as NorthwindModel. Then click Finish.

This results in an EDMX file, which in design view, shows the various entities in the model and how they relate to each other, much like a database diagram in SQL Server Management Studio.

The EDMX file is an XML file that defines the storage model - that is the database itself, the conceptual model - that is the entities as classes, and how the two map to each other. The final part of the XML document is an XML representation of the design view that you see in the preceding image.

Once that has been done, you are ready to work with EF. To test, alter the code in Default.cshtml as follows, making sure that you add the using directive at the top of the page:

@using NorthwindModel;
@{  
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Welcome to my Web Site!";
    var db = new NorthwindEntities();
    var products = db.Products.Where(p => p.CategoryID == 2);
    var grid = new WebGrid(products);
}
<div>
    @grid.GetHtml()
</div>

Launch the page in a browser. The result should look similar to the following image.

Microsoft introduced the Database helper with WebMatrix to make data access easy for beginners or people who know a little SQL, and that's fine. However, the Web Pages framework is built on top of ASP.NET and has the whole of the .NET framework behind it, so the Entity Framework, and indeed LINQ to SQL is available to Web Pages developers who want to use these technologies. WebMatrix doesn't include the tooling to make this happen, but Visual Web Developer Express 2010 SP1 does, and it also includes tooling for working with SQL Server Compact databases - and it's free.

 

Date Posted:
Last Updated:
Posted by:
Total Views to date: 39424

7 Comments

- reav

Now maybe its time for Dapper article and rabbit framework?

- Robby

I have been using EF 4.0 with my SQL 4.0 DB and I love it.

However, I was led to believe that LINQ-to-SQL would not work with SQL CE 4.0.

I am using LINQ-to-Entities and it works fine. If your database design is moderately complex and involves a lot of relationships (resulting in a lot of JOINs), EF really makes things easier and, assuming you're using VWD 2010 SP1, the intellisense you get from the strongly-typed entities (vs the non-typed dynamic records) is a blessing.

- Jason

Hi Mike, I am just following the tutorial and where you wrote: "...choose Add New Item. From the options available, select ADO.NET Entity Data Model..." - I did that, but I don't have ADO.NET Entity Data Model showing up in my list. I have Visual Studio Ultimate 2010 - I'm going to try and see if I can download it?

- Mike

@Jason,

You should find ADO.NET Entity Data Model as an option in the Data section of the menu

- faisal

its a great example for a beginner but could you add CRUD methods too by using Database First and EntityFramework

that would help alot of people other than me

- Matt

I discovered that when using EDMX (with MVC4) you have to create a "buddy class" if you want to add data annotations to your entities, since the EDMX file can be over-written if you refresh from the database. None of the posts I read mentioned this, but it works easiest if your EDMX and buddy class are in the same namespace. Since files grab the namespace of the folder they are in, I placed them both in the Models folder. Here are a couple links about using the MetadatType attribute and buddy classes.

http://stackoverflow.com/questions/8689375/mvc-model-from-edmx-file-add-custom-annotations-to-it-and-make-them-stay

http://hartzer.wordpress.com/2010/01/26/mvc-buddy-class/

- Mike

@Matt,

Recommended practice is to use of ViewModels and to apply attributes to their properties.

Recent Comments

Gayan 7/3/2015 6:20 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
Great Article thanks...

Semil 7/1/2015 7:03 AM
In response to iTextSharp - Drawing shapes and Graphics
I have created a rectangle using above methode. Now I want to add a text in the center of this How I...

Satyabrata Mohapatra 6/30/2015 6:12 PM
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Ahh.....this is awesome. Happy to see after a long time you wrote a article on web form :D...

Marty 6/30/2015 7:16 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, you're the Man! Another great article. So incredibly helpful. I'm definitely going to buy your...

Rohan 6/30/2015 5:32 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Very good and helpful tutorial. Thanks. Just wanted to know what would be the max file size limit we...

Fernando 6/30/2015 1:59 AM
In response to Programmatically accessing data from DataSource controls
What if I want to pass parameters natively using the DataSourceSelectArguments object, instead of be...

pankaj 6/29/2015 3:13 PM
In response to How to retain carriage returns or line breaks in an ASP.NET web page
very nice i'm use this in my code thank you.... ...

Mike 6/29/2015 2:22 AM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
This is the first example that I have found that works....

Marty 6/28/2015 4:57 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, what if I don't want to render back the text to the browser, but I want to send it some other...

Mike 6/27/2015 4:00 PM
In response to Migrating Classic ASP To ASP.NET Razor Web Pages Part One- Razor Syntax And Visual Basic
have you used any of the code converters to convert classic asp to c#? If so, which one do you have...