• No results found

Adding the model

In document ASP.NET.MVC.4.in.Action.pdf (Page 57-61)

Hello MVC world

2.3 The Guestbook sample application

2.3.2 Adding the model

The model for the Guestbook application will be very simple—a single class that rep-resents a guestbook entry is all that we’ll need. We’ll call this class GuestbookEntry, add it to the Models directory in the project, and add a few properties to it:

public class GuestbookEntry {

public int Id { get; set; } public string Name { get; set; } public string Message { get; set; } public DataTime DateAdded { get; set; } }

Figure 2.9 The Server Explorer allows you to add new tables to SQL Server or SQL Server Compact databases.

This model is very simple—it is just a Plain Old CLR Object (POCO) containing four properties that match the columns in the database. We’re going to use instances of this class to represent the data stored in the database, but how will we convert the data in the database into objects? We could manually write the mapping code necessary to hydrate GuestbookEntry instances from the results of SQL queries, but it’s simpler to rely on an object-relational mapping (ORM) tool to do this for us.

For this application, we’ll be using Entity Framework 4.1 to do the mapping for us, although there are many other ORM tools to choose from on the .NET platform (we’ll be looking at NHibernate, another ORM tool, in chapter 15). Although the Entity Frame-work is a large enough topic to have several books dedicated to it (such as Programming Entity Framework by Julia Lerman and Entity Framework 4 in Action by Stefano Mostarda, Marco De Sanctis, and Daniele Bochicchio), Entity Framework 4.1 contains a simplified API that provides an easy way to get started with using Entity Framework for performing data access.

To make use of Entity Framework, we’ll add a DbContext class to the application.

The DbContext provides an abstraction over the Entity Framework that allows us to persist and retrieve data. We’ll create a class called GuestbookContext that also resides in the Models directory of the application. The implementation for this class is shown in the following listing.

Figure 2.10 The definition of the GuestbookEntries table with four columns—the Id, the name of the person signing the guestbook, their message, and the date the message was added.

using System.Data.Entity;

namespace Guestbook.Models {

public class GuestbookContext : DbContext {

Data.Entity namespace), and it begins by declaring a parameterless constructor that uses constructor chaining to pass the name of the database to the base class

B

. In this case, as our database is called Guestbook.sdf, we pass the string "Guestbook" to the base constructor. If we don’t do this, Entity Framework will default to using the full type-name of the context class as the name of the database, and will instead look for a file called Guestbook.Models.GuestbookContext.sdf.

Our context also defines a single property, Entries,

C

which is of type DbSet<GuestbookEntry>. This property acts as a collection that allows us to query the data in the GuestbookEntries table as though it were an in-memory collection of objects. Under the covers, Entity Framework will generate the appropriate SQL to query the table and convert the results into strongly typed GuestbookEntry objects.

We’ll take a look at how to query this collection in section 2.3.4.

Finally, we need to tell Entity Framework that it’s going to be talking to a SQL Server Compact database (by default, it will try to connect to a SQL Server Express instance).

Listing 2.3 The DbContext used for interacting with the database Data access choices

There are many choices available for performing data access in .NET applications.

Many modern applications use ORM tools such as NHibernate or Entity Framework for accessing relational databases, but these are not the only options.

If your application is small, you may decide that you don’t need the additional complexity of an ORM, in which case a simpler tool such as WebMatrix.Data or Simple.Data may be sufficient.

WebMatrix.Data was released by Microsoft at the same time as ASP.NET MVC 3 as part of the ASP.NET Web Pages suite of products, and it provides a lightweight means of performing data access, making use of raw SQL statements and the DLR’s dynamic types. Simple.Data provides a similar solution, but relies on a dynamic query syntax rather than SQL strings. More information about Simple.Data can be found at https://github.com/markrendle/Simple.Data.

To do this, we need to add some initialization code to the application. There are sev-eral ways to achieve this. The first is to manually add the code to the Application_Start method within the Global.asax.cs file. This is a special method that runs once when an application is started (typically when the first visitor hits the web server). However, instead of doing this we’ll take a slightly different approach—

we can use a NuGet package to add the initialization code for us.

NuGet is a package manager tool that allows open-source libraries to quickly and easily be added to any .NET project.

Although NuGet is not tied to ASP.NET MVC projects, it does ship as part of the ASP.NET MVC installer so you can start using it right away without having to per-form a separate install. This functionality is found in a package called EntityFrame-work.SqlServerCompact, which can be installed by right-clicking on the Refer-ences node within the project and select-ing Manage NuGet Packages, as shown in figure 2.11.

This will open a dialog box where you can search for packages in the NuGet Gal-lery. To do this, click the Online item on the left side of the screen, and then enter EntityFramework.SqlServerCompact in the search box in the upper right, as shown in figure 2.12. This should locate a single match, which can then be installed by click-ing the Install button.

NOTE As well as the Manage NuGet Packages dialog box, NuGet also pro-vides a PowerShell-based command line available within Visual Studio that can be launched by clicking View > Other Windows > Package Manager Console. You can install the package using this console instead of the GUI by issuing the command Install-Package.

Once installed, this package will automatically add the relevant code to the project to configure Entity Framework for use with SQL Server Compact databases.

Generating the database from the model

In this example, we created the database first in order to showcase the design-time support that Visual Studio has for SQL Server Compact. But creating the database first isn’t actually necessary.

If you attempted to use the model without first creating the database, Entity Framework is clever enough to realize this and will create the database, tables, and columns for you the first time you try to use it.

Figure 2.11 The NuGet package manager UI can be launched via the Manage NuGet Packages context menu item.

Our newly created model classes will form the core of our application, but we need some way for users of the application to create instances of our model so that the com-ments can be persisted to the database. To do this, we’ll add a controller to the appli-cation, which will be responsible for accepting user input.

In document ASP.NET.MVC.4.in.Action.pdf (Page 57-61)