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

4.82 (17 votes)

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);

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: 50170


- 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


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.

- Mike


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

Recent Comments

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....