Archive for the 'Community News' Category

August 29th Links: .NET, ASP.NET, IIS Express, Silverlight, Windows Phone 7

Here is the latest in my link-listing series.  Also check out my VS 2010 and .NET 4 series and ASP.NET MVC 2 series for other on-going blog series I’m working on.

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

.NET/WPF/EF

  • 5 Little C#/.NET Wonders that Make Code Better: Nice blog post from James that highlights 5 nice language/framework tips you can take advantage of within your apps.  I’m betting a lot of people didn’t know about the StopWatch class.

  • WPF Ribbon Control Released: The WPF team recently released the final V1 release of the WPF Ribbon control.  This makes it easy to build ribbon-based applications. Also read this WPF team blog post for lots of great details on what it enables.

  • EF4 .Include() Method w/ Lambda Support: Ever wanted to use a Lambda expression instead of a string parameter when eagerly loading associations in EF4 using the Include() method?  This blog post shows you how you can.

ASP.NET

  • Techniques to Avoid Duplicate URLs: Scott Mitchell has another great article that discusses techniques you can use within ASP.NET to avoid exposing duplicate URLs to the same content within your web-sites.  These can help improve your search engine traffic.

ASP.NET MVC

  • MvcContrib Template Gallery: Download 58 pre-built ASP.NET MVC Template Gallery styles that you can use to customize the look and feel of your applications. All available under a Community Commons license.

  • Installation Options for ASP.NET MVC: Jon has a good post that describes how to install ASP.NET MVC 2 on a server. There are a couple of options you can use for servers that don’t already have ASP.NET MVC installed – the easiest is to just enable the “Copy Local” flag on System.Web.Mvc.dll and install it in the \bin directory.

IIS Developer Express

  • How to Use IIS Express with VS today: Kamran has a nice blog post that describes how you can use IIS Express with Visual Studio today – without having to wait for the official Visual Studio patch to enable it.

Silverlight and Windows Phone 7

  • Developers Roadmap for Windows Phone 7: The Windows Phone 7 team blogs about the release timeframe for Windows Phone 7 and the Visual Studio and Expression Blend tools for targeting it.  The official developer release will be on September 16th.

  • Windows Phone 7 in 7 Minutes: Really nice set of 7 minute videos that enable you to quickly understand and learn Windows Phone 7 and the development fundamentals behind it.

  • Windows Phone 7 Jumpstart Training: Nice list of free training sessions you can watch online to learn how to build Windows Phone 7 applications using Silverlight and XNA.

  • Using XNA from Silverlight on Windows Phone 7: Good blog post from Mike that demonstrates how to use XNA APIs from Silverlight applications on Windows Phone 7.  This post demonstrates how to use the XNA audio framework from Silverlight.

Book Recommendation

People often ask me for .NET book recommendations. Below is one book I always keep close by and find super-useful.  If you are looking for a good one-volume C# and .NET Base Class Library reference, C# 4.0 in a Nutshell a great one:

ir[1]nutshell

Hope this helps,

Scott

Patch for VS 2010 Find and Replace Dialog Growing

One of the top reported Microsoft Connect issues with VS 2010 has been an issue with the Find and Replace dialog – which grows 16px each time you use it (which is pretty annoying).

The Visual Studio team recently released a patch that fixes this issue. You can download and apply it here.

Hope this helps,

Scott

P.S. A few people reported issues installing the patch if they had an older version of the Silverlight 4 tools installed.  If you see an error message that says you need an update to Visual Studio to support Silverlight 4, you can fix it by installing the latest Silverlight 4 tools release.

“Unplugged” online chat with me this Wednesday

I just got back from my trip to India and the UK last week – and will be returning to more regular blogging shortly. 

This Wednesday (August 18th) I’m going to be doing another online LIDNUG chat session.  The chat will be from 10:00am to 11:30am Pacific Time.  I do these chats a few times a year and they tend to be pretty good.  Attendees can submit any questions they want to me, and listen to me answer them live via LiveMeeting.  You can learn more about it here and join the chat and ask questions at the appropriate time with this link.

Hope to get a chance to chat with some of you there!

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

London “Guathon” Event with Me on August 13th

The (awesome) UK developer community is holding an all day event with me in London on August 13th.  The event is free to attend, and the venue will be in Central London (at the ODEON Covent Garden).  The website for the event is here.

Content

The event will be a packed day of presentations covering VS 2010, ASP.NET 4, ASP.NET MVC, and Silverlight for Windows Phone 7.  Below is the list of talks:

VS 2010 and ASP.NET 4 (90 minutes)

A demo heavy talk that covers some of the new features and capabilities within Visual Studio 2010 and ASP.NET 4, and how you can best take advantage of them.

ASP.NET MVC 2 (90 minutes)

A demo heavy talk that covers using ASP.NET MVC 2 with Visual Studio 2010.  We’ll spend 90 minutes building a new ASP.NET MVC 2 application starting from File->New Project, and explain the core concepts behind ASP.NET MVC, as well as how to take advantage of the new features shipped with ASP.NET MVC 2.

Windows Phone 7 Development (90 minutes)

In this session we’ll take a look at Windows Phone 7 and the developer ecosystem, from the capabilities and unique features of the platform to the development frameworks and tools you have at your disposal. Along the way we’ll build a simple application or two and explore how people can buy your finished masterpiece.

Web Development Futures: ASP.NET MVC 3, SQL CE and IIS Express (90 minutes)

In this session we’ll covers some of the new web technologies shipping in the near future.  Learn about some of the improvements coming with ASP.NET MVC 3, the new “Razor” template syntax, “Code-First” EF4, SQL CE and IIS Express.

Registration

The event is free and only has a few hundred seats – which means they will likely fill up fast (likely in a few hours – or even minutes – if past history is any indication).  So if you want to attend I recommend signing up quickly.

Registration will open tomorrow (Tuesday August 3nd) at 2pm (UK time).  The website for the event and registration is here.

Hope to see some of you there!

Scott

Visual Studio 2010 Keyboard Shortcuts

Earlier this week the Visual Studio team released updated VS 2010 Keyboard Shortcut Posters.  These posters are print-ready documents (that now support standard paper sizes), and provide nice “cheat sheet” tables that can help you quickly lookup (and eventually memorize) common keystroke commands within Visual Studio.

image

This week’s updated posters incorporate a number of improvements:

  • Letter-sized (8.5”x11”) print ready versions are now available
  • A4-sized (210×297mm) print ready versions are now available
  • The goofy people pictures on them are gone (thank goodness)

The posters are in PDF format – enabling you to easily download and print them using whichever paper size is in your printer.

Download the Posters

You can download the VS 2010 Keybinding posters in PDF format here.

Posters are available for each language.  Simply look for the download that corresponds to your language preference (note: CSharp = C#, VB = VB, FSharp = F#, CPP = C++). 

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

Introducing ASP.NET MVC 3 (Preview 1)

This morning we posted the “Preview 1” release of ASP.NET MVC 3.  You can download it here.

We’ve used an iterative development approach from the very beginning of the ASP.NET MVC project, and deliver regular preview drops throughout the development cycle.  Our goal with early preview releases like the one today is to get feedback – both on what you like/dislike, and what you find missing/incomplete.  This feedback is super valuable – and ultimately makes the final product much, much better.

ASP.NET MVC 3

As you probably already surmised, ASP.NET MVC 3 is the next major release of ASP.NET MVC. 

ASP.NET MVC 3 is compatible with ASP.NET MVC 2 – which means it will be easy to update projects you are writing with MVC 2 to MVC 3 when it finally releases.  The new features in MVC 3 build on top of the foundational work we’ve already done with the MVC 1 and MVC 2 releases – which means that the skills, knowledge, libraries, and books you’ve acquired are all directly applicable with the MVC 3 release.  MVC 3 adds new features and capabilities – it doesn’t obsolete existing ones.

ASP.NET MVC 3 can be installed side-by-side with ASP.NET MVC 2, and you can install today’s “Preview 1” release on your machine without it impacting existing MVC 2 projects you are working on (they will continue to use MVC 2 unless you explicitly modify the projects to retarget them to MVC 3).  When you install “Preview 1” you will have a new set of ASP.NET MVC 3 project templates show up within Visual Studio 2010’s “New Project” dialog – choosing one of those when you create a new project will cause it to use MVC 3.

Below are details about some of the new features and capabilities in today’s “Preview 1” release.  Unless otherwise noted, all of the features I describe are enabled with the preview build you can download and use today.  More ASP.NET MVC 3 features will come in future preview refreshes as we flesh out the product more and iterate on your feedback.

View Improvements

ASP.NET MVC 3 “Preview 1” includes a bunch of view-specific improvements.

Add->View Dialog

“Preview 1” includes a new “Add->View” dialog that makes it easy for you to choose the syntax you want to use when you create new view template files.  It allows you to select any of of the available view engines you have installed on your machine – giving you the ability to use whichever view templating approach feels most natural to you:

AddView9

There are a bunch of great open source view template engines out there (including Spark, NHaml, NDjango and more) – it is now much easier for them to integrate into Visual Studio.

Today’s “Preview 1” build of ASP.NET MVC 3 comes with two view-engine already pre-enabled within the dialog: ASPX and Razor. 

New “Razor” View Engine

Earlier this month I blogged about the new “Razor” view engine we’ve been working on.  Based on the comments in the post, a lot of people are eagerly waiting to use it.  The good news is that you can start using it with today’s “Preview 1” release.

Simple Razor Example

Let’s build a super-simple store site that lists product categories, and allows visitors to click the categories to see a listing of products within them.  You can download a completed version of this sample here.

image

Below is a StoreController class that implements the two action methods (“Index” and “Browse”) needed to build the above scenario:

image

We’ll use the new “Razor” view engine to implement the view templates for our StoreController.

Below is the “Layout.cshtml” layout-page that will define the common layout UI we want across our site.  The “RenderBody()” method indicates where view templates that are based on this master layout file should “fill in” the body content:

image

Below is the view template for the Index action.  It is based on the above layout page, and outputs a <ul> list of category names: 

image

The template above is using the standard Html.ActionLink() helper method in ASP.NET MVC to render a hyperlink that links to the “Browse” action method of our StoreController.  All of existing HTML helper methods in ASP.NET MVC work in “Razor” views – this is true both for the HTML helper methods built-into ASP.NET MVC, as well as those built by others (including vendors and the MvcContrib project).

Below is the view template for the Browse action.  It lists the products within a specific category:

image

Notice above how we are using the “Model” property within our foreach statement to access the strongly-typed List of products we passed from our Controller.  We are doing this just like we would within .aspx view templates.  Razor also supports a “View” property which allows us to access un-typed “ViewData” passed to the view template.  “View” is a dynamic property (a new feature of .NET 4) – which gives us a slightly cleaner syntax when accessing ViewData.  Instead of writing ViewData[“Cateogry”] we can now just write View.Category.

Clean and Concise

The code in the screen-shots above contains everything we need to write to implement our Controller + Views.  “Razor” helps make view templates clean and concise, and I think you’ll find it enables a very fluid coding workflow. Read my “Razor” blog post from earlier in the month to learn more about the syntax and understand how it works.  You can download a running version of the above sample here.

Code Intellisense and Colorization

One of the things you might have noticed from the screen-shots above is that “Razor” file colorization and code intellisense is not yet supported in Visual Studio with today’s “Preview 1” release.  We will be enabling full code intellisense and colorization with a future preview refresh.  The VS 2010 editor will support Razor file intellisense for C#/VB code, as well as for HTML/CSS/JavaScript. 

Other Improvements in the Future

Two other enhancements we are working to enable in a future preview refresh are:

  • The ability to use a @model statement at the top of a “Razor” file instead of having to explicitly inherit from a base class.  This reduces the code and simplifies it.  
  • The ability to specify a default LayoutPage for the site to avoid having to explicitly set it within each view template.  This further reduces the code within the view template, and makes your code more DRY.

With these changes the above Browse template will be able to be written as simply:

image

The above template will be supported in a future preview refresh.  Full colorization and code-intellisense will be provided within the editor.

Controller Improvements

ASP.NET MVC 3 “Preview 1” includes several nice controller-specific enhancements.

Global Filters

ASP.NET MVC supports the ability to declaratively apply “cross-cutting” logic using a mechanism called “filters”.  You can specify filters on Controllers and Action Methods today using an attribute syntax like so:

image

Developers often want to apply some filter logic across all controllers within an application.  ASP.NET MVC 3 now enables you to specify that a filter should apply globally to all Controllers within an application.  You can now do this by adding it to the GlobalFilters collection.  A RegisterGlobalFilters() method is now included in the default Global.asax class template to provide a convenient place to do this (it is then called by the Application_Start() method):

image

The filter resolution logic in MVC 3 is flexible so that you can configure a global filter that only applies conditionally if certain conditions are met (for example: debugging is enabled, or if a request uses a particular http verb, etc).  Filters can also now be resolved from a Dependency Injection (DI) container – more on that below.

New Dynamic ViewModel Property

ASP.NET MVC Controllers have supported a “ViewData” property that enables you to pass data to a view template using a late-bound dictionary API.  For example:

image

The “ViewData” API is still supported in ASP.NET MVC 3.  MVC 3 augments it, though, with a new “ViewModel” property on Controller that is of type “dynamic” – and which enables you to use the new dynamic language support within VB and C# to pass ViewData items using a slightly cleaner syntax than the current dictionary API.  Now you can alternatively write the following code to achieve the same result as above:

image

You do not need to define any strongly-typed classes to use the ViewModel property.  Because it is a “dynamic” property you can instead just get/set properties on it and it will resolve them dynamically at runtime.  It internally stores the property name/value pairs within the ViewData dictionary.

New ActionResult Types

ASP.NET MVC 3 “Preview 1” includes several new ActionResult types and corresponding helper methods.

HttpNotFoundResult

The new HttpNotFoundResult class is used to indicate that a resource requested by the current URL was not found. It returns a 404 HTTP status code to the calling client. You can optionally use the new HttpNotFound() helper method on Controller to return an instance of this action result type, as shown in the following example:

image

Permanent Redirects

The HttpRedirectResult class has a new Boolean “Permanent” property that is used to indicate whether a permanent redirect should occur. A permanent redirect uses the HTTP 301 status code.  In conjunction with this change, the Controller class now has three new methods for performing permanent redirects: RedirectPermanent(), RedirectToRoutePermanent(), and RedirectToActionPermanent().  These methods return an instance of HttpRedirectResult with the Permanent property set to true.

HttpStatusCodeResult

The new HttpStatusCodeResult class can be used to set an explicit response status code and description. 

JavaScript and AJAX Improvements

ASP.NET MVC 3 includes built-in JSON binding support that enables action methods to receive JSON-encoded data and model-bind it to action method parameters. 

To see this feature in action, consider the jQuery client-side JavaScript below.  It defines a “save” event handler that will be invoked when a save button is clicked on the client.  The code within the event handler constructs a client-side JavaScript “product” object with three fields whose values are retrieved from HTML input elements.  It then uses jQuery’s .ajax() method to POST a JSON based request containing the product to a /Store/UpdateProduct URL on the server:

image

ASP.NET MVC 3 now enables you to implement the /Store/UpdateProduct URL on the server using an action method like below:

image

The UpdateProduct() action method above accepts a strongly-typed Product object as a parameter.  ASP.NET MVC 3 can now automatically bind the incoming JSON post values to the .NET Product type on the server – without you having to write any custom binding or marshalling logic.  ASP.NET MVC’s built-in model and input validation features all work as you’d expect with this.

We think this capability will be particularly useful going forward with scenarios involving client templates and data binding (like I’ve previously blogged about here).  Client templates will enable you to format and display a single data item or set of data items by using templates that execute on the client.  ASP.NET MVC 3 will enable you to easily connect client templates with action methods on the server that return and receive JSON data.

Other JavaScript/AJAX Improvements in the Future

Future preview refreshes of ASP.NET MVC 3 will include better support for unobtrusive JavaScript.  ASP.NET MVC 3 will also directly support the jQuery Validation library from within its built-in validation helper methods.

Model Validation Improvements

ASP.NET MVC 2 came with significant model validation improvements.  You can read my previous blog post to learn more about them.

ASP.NET MVC 3 extends this work further, and adds support for several of the new validation features introduced within the System.ComponentModel.DataAnnotations namespace in .NET 4. In particular:

  • MVC 3 supports the new .NET 4 DataAnnotations metadata attributes such as DisplayAttribute.
  • MVC 3 supports the improvements made to the ValidationAttribute class in .NET 4.  The ValidationAttribute class was improved in .NET 4 to support a new IsValid overload that provides more information about the current validation context, such as what object is being validated.  This enables richer scenarios where you can validate the current value based on another property of the model. 
  • MVC 3 supports the new IValidatableObject interface introduced in .NET 4.  The IValidatableObject interface enables you to perform model-level validation, and enables you to provide validation error messages specific to the state of the overall model, or between two properties within the model. 

Below is an example of using the IValidatableObject interface built-into .NET 4 to implement a custom validation method on a class.  This method can apply validation rules across multiple properties and yield back multiple validation errors (and optionally include both an error message like below as well as a list of property names that caused the violation):

image

ASP.NET MVC 3 now honors the IValidateObject interface when model binding (in addition to all of the other validation approaches it already supported with MVC 2), and will retrieve validation errors from it and automatically flag/highlight impacted fields within a view using the built-in HTML form helpers:

image

ASP.NET MVC 3 also introduces a new IClientValidatable interface that allows ASP.NET MVC to discover at runtime whether a validator has support for client validation.  This interface has been designed so that it can be integrated with a variety of validation frameworks.  MVC 3 also introduces a new IMetadataAware interface that simplifies how you can contribute to the ModelMetadata creation process. 

Dependency Injection Improvements

ASP.NET MVC 3 provides better support for applying Dependency Injection (DI) and integrating with Dependency Injection/IOC containers.

In “Preview 1”, we’ve added support for dependency injection in the following places:

  • Controllers (registering & injecting controller factories, injecting controllers)
  • Views (registering & injecting view engines, injecting dependencies into view pages)
  • Action Filters (locating & injecting filters)

For future previews we are investigating adding dependency injection support for:

  • Model Binders (registering & injecting)
  • Value Providers (registering & injecting)
  • Validation Providers (registering & injecting)
  • Model metadata Providers (registering & injecting)

ASP.NET MVC 3 will support the Common Service Locator library, and any DI container that supports it’s IServiceLocator interface.  This will make it really easy to integrate any DI container that supports the Common Service Locator with ASP.NET MVC.

Note: In Preview 1, we redefined the CSL interface in our codebase, and didn’t include the CSL DLL in our setup. This means that existing implementations of CSL won’t “just work” with “preview 1” – instead they’ll have to recompile their CSL implementations against our interface to make them work. Future preview refreshes will make this CSL library dependency easier, and avoid this extra step.

Brad Wilson is starting a great blog series on ASP.NET MVC 3’s Dependency Injection Support.  Below are links to his first few articles about it:

Click here to download a simple ASP.NET MVC 3 example that demonstrates how to use the popular Ninject Dependency Injection Container with ASP.NET MVC 3. 

Downloads and Links

Click here to download ASP.NET MVC 3 Preview 1.  Post feedback/issues about it in the ASP.NET MVC Forum.

Once ASP.NET MVC 3 is installed, you can download and run the simple Razor sample I demonstrated in the blog post above. 

Read my previous “Razor” blog post to learn more about how it works and its syntax.  Also read my recent EF4 Code-First and EF4 Code-First Schema Mapping posts to learn more about the database code and clean model layer I built using EF4 Code-First and SQL Express within the above sample.

Summary

We are excited to get today’s ASP.NET MVC 3 “Preview 1” release in people’s hands, and start receiving feedback on it. 

Our primary goal with these early preview releases is to get feedback – both on what you like/dislike, and what you find missing/incomplete.  This feedback is super valuable – and ultimately makes the final product much, much better.  If you do install today’s “Preview 1” build, please post your feedback and any bugs/issues you find to the ASP.NET MVC forum at http://forums.asp.net.  The team will be monitoring this forum closely, and will be happy to help with anything you run into. 

We will then iterate on the feedback you send us, and further refine ASP.NET MVC 3 in future preview refreshes.

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

Entity Framework 4 “Code-First”: Custom Database Schema Mapping

Last week I blogged about the new Entity Framework 4 “code first” development option.  The EF “code-first” option enables a pretty sweet code-centric development workflow for working with data.  It enables you to:

  • Develop without ever having to open a designer or define an XML mapping file
  • Define model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything

In last week’s blog post I demonstrated how to use the default EF4 mapping conventions to enable database persistence.  These default conventions work very well for new applications, and enable you to avoid having to explicitly configure anything in order to map classes to/from a database. 

In today’s blog post I’m going to discuss how you can override the default persistence mapping rules, and use whatever custom database schema you want.  This is particularly useful for scenarios involving existing databases (whose schema is already defined and potentially can’t be changed) as well as for scenarios where you want your model shape to be different than how you want to persist it within a relational database.

Quick Recap of our NerdDinner Sample

In my blog post last week I walked through building a simple “NerdDinner” application from scratch, and demonstrated the productivity gains EF “code first” delivers when working with data. 

image

Below are the two model classes we created to represent data within the application.  They are “plain old CLR objects” (aka “POCO”) that only expose standard .NET data types:

image

We then created a “NerdDinners” class to help map these classes to/from a database.  “NerdDinners” derives from the DbContext class provided by the EF “code first” library and exposes two public properties:

image

We used the default EF4 “code first” conventions to enable database persistence.  This means that the “Dinners” and “RSVPs” properties on our “NerdDinners” class map to tables with the same names within our database.  Each property on our “Dinner” and “RSVP” model classes in turn map to columns within the “Dinners” and “RSVPs” tables.

Below is the database schema definition for the “Dinners” table within our database:

image

Below is the database schema definition for the “RSVPs” table within our database:

image

We did not have to configure anything in order to get this database persistence mapping with EF4 “code first” – this occurs by default simply by writing the above three classes.  No extra configuration is required.

Enabling Custom Database Persistence Mappings with EF4

EF4 “Code First” enables you to optionally override its default database persistence mapping rules, and configure alternative ways to map your classes to a database.

There are a few ways to enable this.  One of the easiest approaches is to override the “OnModelCreating” method defined on the DbContext base class:

image

The OnModelCreating method above will be called the first time our NerdDinners class is used within a running application, and it is passed a “ModelBuilder” object as an argument.  The ModelBuilder object can be used to customize the database persistence mapping rules of our model objects.  We’ll look at some examples of how to do this below.

EF only calls the “OnModelCreating” method once within a running application – and then automatically caches the ModelBuilder results.  This avoids the performance hit of model creation each time a NerdDinners class is instantiated, and means that you don’t have to write any custom caching logic to get great performance within your applications.

Scenario 1: Customize a Table Name

Let’s now look at a few ways we can use the OnModelCreating method to customize the database persistence of our models.  We will begin by looking at a pretty common scenario – where we want to map a model class to a database schema whose table names are different than the classes we want to map them to. 

For example, let’s assume our database uses a pattern where a “tbl” prefix is appended to the table names.  And so instead of a “Dinners” table we have a “tblDinners” table in the database: 

image

We want to still map our clean “Dinners” model class to this “tblDinners” table – and do so without having to decorate it with any data persistence attributes:

image

We can achieve this custom persistence mapping by overriding the “OnModelCreating” method within our NerdDinners context class, and specify a custom mapping rule within it like so:

image

The code within our OnModelCreating() method above uses a Fluent API design – which is a style of API design that employs method chaining to create more fluid and readable code.  We are using the ModelBuilder object to indicate that we want to map the “Dinner” class to the “tblDinners” table. 

And that is all the code we need to write.  Now our application will use the “tblDinners” table instead of the “Dinners” table anytime it queries or saves Dinner objects.  We did not have to update our Dinner or RSVP model classes at all to achieve this – they will continue to be pure POCO objects with no persistence knowledge.

Trying out the Above Change

If you downloaded the completed NerdDinner sample from my previous blog post, you can modify it to include the above custom OnModelCreating() method and then re-run it to see the custom database persistence in action.

We enabled the automatic database creation/recreation feature within EF “code-only” with the previous blog post.  This means that when you re-run the downloaded NerdDinner application immediately after making the above OnModelCreating() code change, you’ll notice that the SQL CE database is updated to have a “tblDinners” table instead of a “Dinners” table.  This is because EF detected that our model structure changed, and so re-created the database to match our model structure.  It honored our custom OnModelCreating() mapping rule when it updated it – which is why the table is now “tblDinners” instead of “Dinners”.

Several people asked me at the end of my first blog post whether there was a way to avoid having EF auto-create the database for you.  I apparently didn’t make it clear enough that the auto-database creation/recreation support is an option you must enable (and doesn’t always happen).  You can always explicitly create your database however you want (using code, .sql deployment script, a SQL admin tool, etc) and just point your connection string at it – in which case EF won’t ever modify or create database schema.

I showed the auto-database creation feature in the first blog post mostly because I find it a useful feature to take advantage of in the early stages of a new project.  It is definitely not required, and many people will choose to never use it.

Importantly we did not have to change any of the code within the Controllers or Views of our ASP.NET MVC application.  Because our “Dinner” class did not change they were completely unaffected by the database persistence change.

Scenario 2: Customize Column/Property Mappings

Let’s now look at another common scenario – one where we want to map a model class to a database schema whose table and column names are different than the classes and properties we want to map them to. 

For example, let’s assume our “tblDinners” database table contains columns that are prefixed with “col” – and whose names are also all different than our Dinner class:

image

We still want to map our clean “Dinners” model class to this “tblDinners” table – and do so without having to decorate it with any data persistence attributes:

image

We can achieve this custom persistence by updating our “OnModelCreating” method to have a slightly richer mapping rule like so:

image

The above code uses the same .MapSingleType() and .ToTable() fluent method calls that we used in the previous scenario.  The difference is that we are also now specifying some additional column mapping rules to the MapSingleType() method.  We are doing this by passing an anonymous object that associates our table column names with the properties on our Dinner class. 

The dinner parameter we are specifying with the lambda expression is strongly-typed – which means you get intellisense and compile-time checking for the “dinner.” properties within the VS code editor.  You also get refactoring support within Visual Studio – which means that anytime you rename one of the properties on the Dinner class - you can use Visual Studio’s refactoring support to automatically update your mapping rules within the above context menu (no manual code steps required). 

Scenario 3: Splitting a Table Across Multiple Types

Relational tables within a database are often structured differently than how you want to design your object-oriented model classes.  What might be persisted as one large table within a database is sometimes best expressed across multiple related classes from a pure object-oriented perspective – and often you want the ability to split or shred tables across multiple objects related to a single entity.

For example, instead of a single “colAddr” column for our address, let’s assume our “tblDinners” database table uses multiple columns to represent the “address” of our event:

image

Rather than surface these address columns as 4 separate properties on our “Dinner” model class, we might instead want to encapsulate them within an “Address” class and have our “Dinner” class exposes it as a property like so:

image

Notice above how we’ve simply defined an “Address” class that has 4 public properties, and the “Dinner” class references it simply by exposing a public “Address” property.  Our model classes are pure POCO with no persistence knowledge.

We can update our “OnModelCreating” method to support a mapping of this hierarchical class structure to a single table in the database using a rule like so:

image

Notice how we are using the same mapping approach we used in the previous example – where we map table column names to strongly-typed properties on our model object.  We are simply extending this approach to support complex sub-properties as well.  The only new concept above is that we are also calling modelBuilder.ComplexType<Address>() to register our Address as a type that we can use within mapping expressions.

And that is all we have to write to enable table shredding across multiple objects.

Download an Updated NerdDinner Sample with Custom Database Persistence Rules

You can download an updated version of the NerdDinner sample here.  It requires VS 2010 (or the free Visual Web Developer 2010 Express).

You must download and install SQL CE 4 on your machine for the above sample to work.  You can download the EF Code-First library here.  Neither of these downloads will impact your machine.

Summary

The CTP4 release of the “EF Code-First” functionality provides a pretty nice code-centric way to work with data.  It brings with it a lot of productivity, as well as a lot of power.  Hopefully these two blog posts provides a glimpse of some of the possibilities it provides. 

You can download the CTP4 release of EF Code-First here.  To learn even more about “EF Code-First” check out these blog posts by the ADO.NET team:

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

VS 2010 Productivity Power Tools Update (with some cool new features)

Last month I blogged about the VS 2010 Productivity Power Tools Extensions – a free set of Visual Studio 2010 extensions that provide some really nice additional functionality.

The initial Visual Studio Productivity Power Tools release included a bunch of really useful productivity enhancements – including a much faster “Add Reference” dialog, lots of code editor additions and enhancements, and some nice IDE improvements around document tab management.  You can learn more about these features in my previous blog post.

VS 2010 Productivity Power Tools Update

Yesterday we shipped an update to the VS 2010 Productivity Power Tools which adds some nice new features and enhancements.

If you already have the VS 2010 Productivity Power Tools installed, you can update it to the latest release by choosing Visual Studio’s “Tools->Extension Manager” menu command.  This will bring up the VS 2010 Extension Manager – which allows you to browse and download new extensions.  If you click the “Updates” tab on the left-hand side of the dialog it also allows you to see any updates that are available for extensions you already have installed within your IDE.

Simply click the “Update” button for the Productivity Power Tools extension and it will download and install an update for it:

image

If you don’t already have the VS 2010 Productivity Power Tools installed, you can download and install it here.

Sean has a nice blog post that describes all of this week’s productivity power tool updates and additions.  Below are a few of the highlights:

Tools Options Support

The top feature request with the productivity power tools has been to have the ability to turn on/off individual features and extensions it provides. 

With last month’s release you couldn’t easily turn individual features on and off.  Starting with this week’s update you can use Tools->Options within VS 2010, and use a new Productivity Power Tools section to easily enable/disable each feature individually:

image

In addition to enabling/disabling individual features, you can also tweak/edit their settings (including color schemes and behavior).

Solution Navigator

Solution Navigator is a new VS 2010 tool window provided with this week’s update.  It acts like an enhanced Solution Explorer.  It merges functionality from Solution Explorer, Class View, Object Browser, Call Hierarchy, Navigate To, and Find Symbol References all into one tool window – and is pretty darn cool.  Here are just two scenarios of how you can take advantage of it:

File + Class Explorer in One

You can use the “Solution Navigator” to browse your project just like you would with the standard “Solution Explorer” tool window today.  Except instead of ending with only file sub-nodes, you can now expand them to see classes as well as individual methods and members within them. Clicking on one of the sub-nodes will navigate you immediately to the appropriate code block within the code editor.

For example, below we’ve expanded the \Controllers folder within an ASP.NET MVC project and drilled into the AccountController.cs file – which has a AccountController class within it.  We can now drill into that class within the “Solution Navigator” to see a listing of all of its members – and double-click any of them to jump to it within the code editor:

image

Filter Solution

You might have noticed the search box that is at the top of the Solution Navigator above.  You can search within it to quickly filter your solution view. 

For example, below I’ve entered the string “Log” – which causes the “Solution Navigator” to automatically filter to only show those files and members that contain the word “Log” in their names (everything else is hidden within the explorer).  Notice below how my filtered views displays a “view template” file named “LogOn.cshtml”, the three “LogXYZ” methods within my AccountController class, the LogOnModel class within the AccountModels.cs file, and several tests within my test project whose names contain Log:

image

You can double click any of the filtered files or members to immediately navigate to it within the code editor.

Quick Access

Quick Access is a new VS 2010 tool window that allows you to quickly search for and execute common tasks within the IDE.  Ever wondered where a particular menu command is located?  Or ever struggled to find a specific option within the Tools->Options dialog?  Just enter it within Quick Access and it will help you locate it:

image

Clicking any of the items within the list will execute the command, or take you to the appropriate place in the IDE where it lives (in the case of Tools->Options settings):

image

Above I searched for “format” and brought up all the tools->options format settings.  Clicking the “Text Editor->C#->Formatting->New Lines” item within the list opens up the Tools-Options dialog to that exact option location.

Summary

I’ve only touched on a few of the improvements with this week’s update.  Read Sean’s blog post for even more details on the updates and improvements.

If you haven’t installed the free VS 2010 Productivity Power Tools, I highly recommend doing so – I think you’ll find some useful extensions that you’ll like.  If you already have last month’s release installed, you can easily update it to this week’s release to take advantage of even more cool features – as well as benefit from bug fixes and performance improvements.

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

Code-First Development with Entity Framework 4

.NET 4 ships with a new and much improved version of Entity Framework (EF) – a data access and OR/M  library that lives within the System.Data.Entity namespace.

When Entity Framework was first introduced with .NET 3.5 SP1, developers provided a lot of feedback on things they thought were missing or incomplete with that first release.  The SQL team did a good job of listening to this feedback, and really focused the EF that ships with .NET 4 on addressing it.  Some of the big improvements in EF4 include:

  • POCO Support: You can now define entities without requiring base classes or data persistence attributes.
  • Lazy Loading Support: You can now load sub-objects of a model on demand instead of loading them up front.
  • N-Tier Support and Self-Tracking Entities: Handle scenarios where entities flow across tiers or stateless web calls.
  • Better SQL Generation and SPROC support: EF4 executes better SQL, and includes better integration with SPROCs
  • Automatic Pluralization Support: EF4 includes automatic pluralization support of tables (e.g. Categories->Category).
  • Improved Testability: EF4’s object context can now be more easily faked using interfaces.
  • Improved LINQ Operator Support: EF4 now offers full support for LINQ operators.

Visual Studio 2010 also includes much richer EF designer and tooling support. The EF designer in VS 2010 supports both a “database first” development style – where you construct your model layer on a design surface from an existing database.  It also supports a “model first” development style – where you first define your model layer using the design surface, and can then use it to generate database schema from it.  It also enables you to customize the code generated by the designer using T4 code templates.

Code-First Development with EF

In addition to supporting a designer-based development workflow, EF4 also enables a more code-centric option which we call “code first development”.  Code-First Development enables a pretty sweet development workflow, and I think makes working with data both a lot simpler and a lot more powerful.  It enables you to:

  • Develop without ever having to open a designer or define an XML mapping file
  • Define your model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally override the convention-based persistence and use a fluent code API to fully customize the O/R persistence mapping

EF’s “code first development” support is currently enabled with a separate download that runs on top of the core EF built-into .NET 4.  CTP4 of this “code-first” library shipped this week and can be downloaded here

It works with VS 2010 (including express editions) and you can use it with any .NET 4 project (including both ASP.NET Web Forms and ASP.NET MVC).

Step by Step Tutorial: Building NerdDinner using a Code-First Approach

Last year I wrote an ASP.NET MVC 1 tutorial that was published both online in an HTML/PDF format as well as within a book from WROX press.  The tutorial walked through creating a simple application called “NerdDinner” which provides an easy way for people to organize, host and RSVP for dinners online.  You can read my original ASP.NET V1 NerdDinner tutorial here.  An updated version of the tutorial is also included in the new Professional ASP.NET MVC 2 book.

The NerdDinner tutorials (both the V1 and V2 versions) used a “database first approach” where the database schema was defined first, and then we used a Visual Studio designer to create our LINQ to SQL/LINQ to Entities model objects that mapped to it.  

Below we will walkthrough how we could instead use a “code first approach” using EF4 to build the NerdDinner model layer and database schema, and construct a CRUD application using ASP.NET MVC.

image

We’ll walkthrough building this application step-by-step.  A link to download a completed version of the application is available at the end of this blog post.

Step 1: Create a New Empty ASP.NET MVC 2 Application

We’ll start by creating a new ASP.NET MVC 2 Project within Visual Studio 2010.  Choose File->New Project and use the “ASP.NET MVC 2 Empty Web Application” project template to do this.

This will create an empty ASP.NET MVC 2 project that does not have any controllers, models or views within it:

image

We’ll next work to define our NerdDinner “model” – which refers to the objects that represent the data of our application, as well as the corresponding domain logic that integrates validation and business rules with it.  The model is the "heart" of an MVC-based application, and fundamentally drives the behavior of it.  We’ll create this model layer using the new EF4 “Code First” capabilities.

Step 2: Create our Model

Let’s assume we do not already have a database defined, and that we are building our new NerdDinner application completely from scratch.

We do not need to start with a database

When using a code-first development workflow, we do not need to begin our application by creating a database or specifying schema.  Instead we can begin by writing standard .NET classes that define the domain model objects that are most appropriate for our application – without having to worry about intermixing data persistence logic within them.

Creating Model Classes

NerdDinner is a small application, and our data storage needs with it are pretty simple.  We want to be able to define and store “Dinners” that refer to specific events that people can attend.  We also want to be able to define and store “RSVP” acceptances, which are used to track a person’s interest in attending a particular Dinner.

Let’s create two classes (Dinner and RSVP) to represent these concepts.  We’ll do this by adding two new classes to our ASP.NET MVC project - “Dinner” and “RSVP”:

image

The above “Dinner” and “RSVP” model classes are “plain old CLR objects” (aka POCO).  They do not need to derive from any base classes or implement any interfaces, and the properties they expose are standard .NET data-types.  No data persistence attributes or data code has been added to them. 

The ability to define model classes without having to tie them to a particular database, database API, or database schema implementation is really powerful – and provides us with much more data access flexibility.  It allows us to focus on our application/business needs without having to worry about persistence implementation.  It also gives us the flexibility to change our database schema or storage implementation in the future – without having to re-write our model objects, or the code that interacts with them.

Creating a Context Class to Handle Database Persistence

Now that we’ve defined our two POCO model classes, let’s create a class that we can use to handle the retrieval/persistence of Dinner and RSVP instances from a database.

We’ll name this class “NerdDinners”. It derives from the DbContext base class, and publishes two public properties – one that exposes our Dinner objects, and one that exposes our RSVP objects:

image

The DbContext and DbSet classes used above are provided as part of the EF4 Code-First library.  You’ll need to add a reference to the System.Data.Entity.CTP assembly that is installed into the \Program Files\Microsoft ADO.NET Entity Framework Feature CTP4\Binaries directory to reference these classes.  You’ll also want to add a “using System.Data.Entity” namespace statement at the top of your “NerdDinners” class file.

That is all the code we need to write

The above three classes contain all of the code necessary to implement a basic model and data persistence layer for our NerdDinner application.  We do not need to configure any additional database schema mapping information, nor run any tools, nor edit any XML files, nor use any designers in order to start using our classes to retrieve, update, and save data into a database.

Convention Based Persistence Mapping

We do not need to write any additional code, nor create any XML files, nor use any tools in order to map our model classes to and from a database.  How, you might ask, is that possible?

By default, EF code-first supports a “convention over configuration” approach that enables you to rely on common mapping conventions instead of having to explicitly configure things.  You can override these conventions if you want to provide custom database mapping rules.  But if you instead just use the default conventions you’ll find that the amount of code you have to write is really small, and the common 90% of scenarios “just work” the way you’d expect them to without any extra code or configuration.

In our example above, our NerdDinners context class will by default map its “Dinners” and “RSVPs” properties to “Dinners” and “RSVPs” tables within a database.  Each row within the Dinners table will map to an instance of our “Dinner” class.  Likewise, each row within the RSVPs table will map to an instance of our “RSVP” class.  Properties within the “Dinner” and “RSVP” classes in turn map to columns within the respective “Dinners” and “RSVPs” database tables.

Other default conventions supported by EF include the ability to automatically identify primary-key and foreign keys based on common naming patterns (for example: an ID or DinnerID property on the Dinner class will be inferred as the primary key).  EF also includes smart conventions for wiring-up association relationships between models.  The EF team has a blog post that talks more about how the default set of conventions work here.

Code Examples of How to Use Our Model

The three classes we created earlier contain all of the code necessary to implement our model and data persistence for NerdDinner.  Let’s now look at a few code examples of how we can use these classes to perform common data scenarios:

Query Using LINQ Expressions

We can write LINQ query expressions to retrieve data from a database using the following code.  Below we are using a LINQ expression to retrieve all dinners that occur in the future:

image

We can also take advantage of relationships between Dinners and RSVPs when writing our LINQ expressions.  Notice below how our “where” statement filters by dinners whose RSVP count is greater than 0:

image

Note that the “where” filter in the above query (where we are retrieving only those Dinners who have at least one RSVP) executes in the database server – making the query and the amount of data we retrieve very efficient.

Retrieving a Single Instance

We can use LINQ’s Single() method with a lambda query to retrieve a single instance of a Dinner using code like below:

image

Alternatively, we can also take advantage of a Find() method that EF “code-first” exposes that allows you to easily retrieve an instance based on its ID:

image

Adding a new Dinner

The code below demonstrates how to create and add a new Dinner to the database.  All we need to do is to “new” a Dinner object, set properties on it, and then add it to the Dinners property of our NerdDinners context object.  The NerdDinner context class supports a “unit of work” pattern that enables you to add multiple models to the context, and then call “SaveChanges()” on it to persist all of the changes to a database as a single atomic transaction.

image

Updating a Dinner

The code below demonstrates how to retrieve a Dinner, update one of its properties, and then save the changes back to the database:

image

Step 3: Create a ASP.NET MVC Controller that uses our Model

Let’s now look at a more complete scenario involving our model, where we use a controller class to implement the functionality necessary to publish a list of upcoming dinners, and enable users to add new ones:

image

We’ll implement this functionality by right-clicking on the “Controllers” folder and choose the “Add->Controller” menu command.  We’ll name our new controller “HomeController”.

We’ll then add three “action methods” within it that work with the NerdDinners model we created earlier using EF “Code-First”:

image

The “Index” action method above retrieves and renders a list of upcoming dinners. 

The “Create” action methods allow users to add new dinners.  The first “Create” method above handles the “HTTP GET” scenario when a user visits the /Home/Create URL, and send back a “New Dinner” form to fill out.  The second “Create” method handles the “HTTP POST” scenario associated with the form – and handles saving the dinner in the database.  If there are any validation issues it redisplays the form back to the user with appropriate error messages.

Adding Views for our Controllers

Our next step will be to add two “View templates” to our project – one for “Index” and one for “Create”. 

We’ll add the “Index” view to our project by moving our cursor within the Index action method of our controller, and then right-click and choose the “Add View” menu command.  This will bring up the “Add View” dialog.  We’ll specify that we want to create a strongly-typed view, and that we are passing in a IEnumerable list of “Dinner” model objects to it:

image

When we click “Add”, Visual Studio will create a /Views/Home/Index.aspx file.  Let’s then add the following code to it – which generates a <ul> list of Dinners, and renders a hyperlink that links to our create action:

image

We’ll then add the “Create” view to our project by moving our cursor within the Create action method of our controller, and then right-click and choose the “Add View” menu command.  Within the “Add View” dialog we’ll specify that we want to create a strongly-typed view, and that we are passing it a Dinner object.  We’ll also indicate that we want to “scaffold” using a “Create” template:

image

When we click “Add”, Visual Studio will create a /Views/Home/Create.aspx file with some scaffold-generated content within it that outputs an HTML <form> for a “Dinner” object.  We’ll tweak it slightly and remove the input element for the DinnerID property.  Our final view template content will look like this:

image

We have now implemented all of the code we need to write within our Controller and Views to implement the Dinner listing and Dinner creation functionality within our web application.

Step 4: The Database

We’ve written our code.  Now let’s run the application. 

But what about the database?

We don’t have a database yet – and haven’t needed one so far because our “code first” development workflow hasn’t required us to have one to define and use our model classes. 

But we will need a database when we actually run our application and want to store our Dinner and RSVP objects.  We can create the database one of two ways:

  1. Manually create and define the schema ourselves using a database tool (e.g. SQL Management Studio or Visual Studio)
  2. Automatically create and generate the schema directly from our model classes using the EF Code-First library

This second option is pretty cool and is what we are going to use for our NerdDinner application.

Configuring our Database Connection String

To begin with, we’ll setup a connection-string to point to where we want our database to live.  We’ll do this by adding a “NerdDinners” connection-string entry to our application’s web.config file like so: 

image 

By default, when you create a DbContext class with EF code-first, it will look for a connection-string that matches the name of the context-class.  Since we named our context class “NerdDinners”, it will by default look for and use the above “NerdDinners” database connection-string when it is instantiated within our ASP.NET application.

Taking advantage of SQL CE 4

You can use many different databases with EF code-first – including SQL Server, SQL Express and MySQL.

Two weeks ago I blogged about the work we are also doing to enable the embedded SQL CE 4 database engine to work within ASP.NET.  SQL CE 4 is a lightweight file-based database that is free, simple to setup, and can be embedded within your ASP.NET applications.  It supports low-cost hosting environments, and enables databases to be easily migrated to SQL Server.

SQL CE can be a useful option to use when you are in the early stages of defining (and redefining) your model layer – and want to be able to quickly create and recreate your database as you do so.  We’ll use SQL CE 4 to begin with as we develop our NerdDinner application.  We can later optionally change the connection-string to use SQL Express or SQL Server for production deployment – without having to modify a single line of code within our application.

The connection-string I specified above points to a NerdDinners.sdf database file, and specifies the SQL CE 4 database provider.  In order for this to work you need to install SQL CE 4 – either via the Standalone SQL CE Installer or by installing WebMatrix (which includes it built-in).  SQL CE 4 is a small download that only takes a few seconds to install.

Important: In the connection-string above I’m indicating that we want to create the NerdDinners.sdf file within the |DataDirectory| folder – which in an ASP.NET application is the \App_Data\ folder immediately underneath the application directory.  By default the “Empty ASP.NET MVC Web Application” project template does not create this directory.  You will need to explicitly create this directory within your project (right click on the project and choose the “Add->ASP.NET Folder->Add_Data” menu item).

Automatic Database Schema Creation

EF code-first supports the ability to automatically generate database schema and create databases from model classes – enabling you to avoid having to manually perform these steps.

This happens by default if your connection-string points to either a SQL CE or SQL Express database file that does not already exist on disk.  You do not need to take any manual steps for this to happen.

To see this in action, we can press F5 to run our NerdDinner application.  This will launch a browser at the root “/” URL of our application.  You should see a screen like below rendered back:

image

The “/” URL to our application invoked the HomeController.Index() action method – which instantiated and queried our NerdDinners context object to retrieve all upcoming Dinners from our database.  Because the NerdDinners.sdf database file we pointed our connection-string to didn’t already exist, the EF code-first library automatically generated it for us.  It used our NerdDinners context object to automatically infer the database schema for the database it generated. 

To see the SQL CE database file that was generated, click the “Show all Files” icon within the Visual Studio solution explorer, and then press the “Refresh” button and expand the App_Data folder:

image 

We will be shipping an update to VS 2010 in the future that enables you to open up and edit SQL CE 4 databases within the “Server Explorer” tab (just like you do with SQL databases today).  This will enable you to easily see (and optionally tweak) the schema and contents of the database.  Until then you can optionally use the database tools within WebMatrix to examine the SQL CE 4 database file’s contents. 

We did not specify any custom persistence mapping rules with our NerdDinners context – so the database that was generated followed the default EF code-first naming conventions to map the schema.  If we had specified any custom mapping rules, though, the EF code-first library would have honored those and generated a database that matched them. 

Just to refresh our memory – here are the two POCO model classes and the NerdDinners context class that we defined earlier:

image

Below are the tables that were added when we ran our application and the database was automatically created based on the above model:

image 

The definition of the “Dinners” table looks like below.  The column names and data-types map to the properties of the Dinner class we defined.  The DinnerID column has also been configured to be both a primary key and an identity column:

image

The definition of the “RSVPs” table looks like below.  The column names and data-types map to the properties of the RSVP class we defined.  The RsvpID column has also been configured to be both a primary key and an identity column:

image

A one to many primary key/foreign key relationship was also established between the Dinners and RSVPs tables.  The EF code-first library inferred that this should be established because our Dinner class has an ICollection<RSVP> property named RSVPs, and the RSVP class has a Dinner property.  

Populating the Database with some Dinners

Let’s now create and add some Dinners to our database.  We’ll do this by clicking the “Create New Dinner” link on our home-page to navigate to our “Create” form:

image

When we click the “Create” button, our new Dinner will be saved in the database.  We can repeat this multiple times to register several different Dinners.  Each new Dinner we create will be persisted within our database and show up in our Home listing of upcoming dinners:

image 

Step 5: Changing our Model

We are going to continually evolve and refactor our model as our application grows.  The EF code-only library includes some nice development features that make it easier to coordinate this evolution with a development database.

Adding a new Property to the Dinner Model

Let’s walkthrough making a simple change to our Dinner class.  Specifically, we’ll add an additional property to our Dinner class called “Country”:

image

Now that we’ve made this change, let’s press F5 in Visual Studio to build and re-run the application.  When we do this we’ll see the below error message:

image

This error message occurs because we’ve changed the structure of our Dinner class, and our model object is now no longer the same shape as the “Dinners” table we automatically created within our database. 

When EF automatically creates a database for you, it by default adds an “EdmMetadata” table to the database that tracks the shape of the model objects that were used to automatically create the database schema for you: 

image

The error message above occurs when EF detects that you’ve made a change to a model object and it is now out of sync with the database it automatically created for you. 

Re-synchronizing our Model Classes with the Database

There are a couple of ways we can “re-sync” our model objects and our database:

  • We can manually update our database schema to match our models
  • We can manually delete our database file, re-run the application, and have EF automatically re-create the database
  • We can enable a feature of EF code-first that automatically updates our database for us whenever we change our models

Let’s look at how we can use this last automatic option with our NerdDinner application.

The RecreateDatabaseIfModelChanges Feature

CTP 4 of the EF Code First library includes a useful development-time feature that enables you to automatically re-create your database anytime you make modifications to your model classes.  When you enable it, EF identifies when any of the model classes that were used to automatically create a database are modified, and when that happens can re-create your database to match the new model class shape – without you having to take any manual steps to do so.

This capability is especially useful when you are first developing an application, since it gives you the freedom and flexibility to quickly refactor and restructure your model code however you want - without having to do any manual work to keep your database schema in sync along the way.  It works especially well with SQL CE – since it is a file-based database that can be dropped and recreated on the fly in under a second.  This can enable an incredibly fluid development workflow.

The easiest way to enable this capability is to add a Database.SetInitializer() call to the Application_Start() event handler within our Global.asax class:

image

This tells EF to re-create our NerdDinners.sdf database to match our NerdDinners model anytime our model classes change shape.  Now when we re-run our application we will no longer get that error message telling us that our model classes and database are out of sync.  EF will instead automatically re-create a database for us that matches our new model class shape, and our application will run fine:

image

Seeding Initial Data in Automatically Created Databases

One of the things you might have noticed in the above screen-shot is that we lost our dinner data when we recreated the database.  This is because the automatic “RecreateDatabaseIfModelChanges” behavior isn’t intended for production scenarios where you want to “migrate” existing data from one schema to another.  Instead it is designed for development scenarios where you want the database to be quickly and automatically updated for you – without you having to take any manual steps or specify migration rules to do so. 

Note: We are separately working to provide better data migration support for scenarios where you are working with production data and want to version the schema.  We think of that as a different scenario than this early development-time feature that I’m describing here.  The data migration capability isn’t enabled yet with this week’s CTP.

EF supports the ability for us to optionally “seed” our generated database with default/test data anytime the database is created/recreated.  I find this feature really useful since it enables me to refactor a model, and then quickly run the application to try out a scenario – without having to enter in a bunch of test data manually to do so.

We can “seed” our NerdDinners database with default data by writing a “NerdDinnersIntializer” class like below.  I’m using it to create two “sample dinners” and adding them to our database like so:

image

We can then update the Database.Initializer() call we added to our Global.asax to use this “NerdDinnersInitializer” class at startup:

image

And now anytime we make a change to one of our NerdDinner model classes, the database will be automatically dropped and recreated to match our models, and we’ll have two dinners already seeded in the database for testing purposes:

image

Easy Refactoring

The above features make it really easy to evolve and refactor your code at development time – without having to use tools or run scripts to manually keep your database in sync with your code changes.

Because our model classes, LINQ expressions, and “seed” test data are all strongly typed, we can also take advantage of refactoring tool support inside Visual Studio to quickly and automatically apply changes across our code base in a quick and easy way.

Step 6: Adding Validation Rules

We’ve built a nice, simple data-entry application.

One problem with it, though, is that we don’t currently have any type of input validation in place to ensure that fields are filled out correctly within our Create Dinner form.  Let’s fix that.

Adding Validation using DataAnnotations

Validation rules in an ASP.NET MVC based application are usually best expressed within a model.  This enables them to be maintained in a single place, and enforced across any number of controllers and views that might interact with them.  ASP.NET MVC enables you to implement validation rules using a variety of different mechanisms, and is flexible enough to support just about any validation scheme you want to use. 

ASP.NET MVC 2 includes built-in support for using .NET’s System.ComponentModel.DataAnnotations library of validation rules – which enable you to declaratively apply validation rules to model classes using validation attributes.  You can learn more about this capability in a previous blog post I wrote.  We’ll take advantage of this approach to enable input validation for our NerdDinner application.

Let’s go back to the Dinner class we defined earlier and add some validation attributes to its properties (note: we need to add a “using System.ComponentModel.DataAnnotations” namespace as well):

image

The [Required] validation attribute indicates that a particular property must be specified.  The [StringLength] validation attribute allows us to indicate a maximum length for a particular string property.  The [RegularExpression] validation attribute allows us to indicate that a particular string property must match a specified regular expression in order to be valid – in this case an email address.

Each of the validation attributes supports an “ErrorMessage” property – which allows us to specify an error message that should be displayed if the validation fails.  This can either be hard-coded as a string (like above) or pulled from a resource – enabling it to be easily localized.

Referencing some CSS and JavaScript files

The last step will be to go back to our Create.aspx view template and add a <link> reference to a Site.css file in our project, as well as two <script> elements that reference two JavaScript files in our project.  We’ll also add one line of code to call Html.EnableClientValidation() before our <form> element is rendered:

image

These changes will ensure that any validation error messages that are displayed in the page are styled (to make them more visible), and that the validation rules we apply on our model will be applied both on the client and on the server.

Running the Application

Let’s re-run the application and try to create a new Dinner.  Let’s begin by pushing the “Create” button with no values filled out.  We’ll find that we now see the validation error messages we applied to our model showing up in the browser:

image

Because we enabled client-side validation with ASP.NET MVC (that was the one line of code we wrote above), our error messages will update and change in real-time:

image

Notice above how our validation error message changed once our “Title” became longer than 20 characters.  This is because we have a [StringLength] property on our Dinner.Title property that indicates a maximum allowed size of 20 characters.  As we started entering a value within the “HostedBy” textbox, our error message likewise changed from the “[Requred]” error message (which asks you to enter your email address) to the “[RegularExpression]” error message (which is telling us we don’t have a valid email address).

These validation rules work both within the browser (via JavaScript) and on the server (enabling us to protect ourselves even if someone tries to bypass the JavaScript validation) – without us having to make any changes to our controller class.  The ability to specify these rules once within our model, and have them apply everywhere, is extremely powerful – and will enable us to continue to evolve our application in a very clean way. 

You can learn more about these ASP.NET MVC 2 Model Validation features and how they work here.

Download

Click here to download and run the above NerdDinnerReloaded sample we’ve built in this blog post.  It requires VS 2010 (or the free Visual Web Developer 2010 Express). 

Important: You must download and install SQL CE 4 on your machine for the above sample to work.  You can download the EF Code-First library here.  Neither of these downloads will impact your machine.

Summary

This week’s CTP4 release of the “EF Code-First” functionality provides a pretty nice code-centric way to work with data.  It brings with it a lot of productivity, as well as a lot of power.  In today’s tutorial I focused mostly on some of the new productivity enhancements provided with the CTP4 release.  There are many more scenarios we could drill into including its Fluent API for enabling custom persistence mapping rules, its improved testability support, and other more advanced capabilities.

You can download this week’s CTP4 release of EF Code-First here.  To learn even more about “EF Code-First” check out these blog posts by the ADO.NET team:

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

Windows Phone 7 Developer Tools Beta Released

Earlier today we shipped the beta of the Windows Phone 7 Developer Tools.  You can download them here.

What is included in the Windows Phone Developer Tools

The Windows Phone Developer Tools Beta includes:

  • Visual Studio 2010 Express for Windows Phone – a new free, express edition of Visual Studio 2010
  • Express Blend for Windows Phone – a new free, edition of Blend focused on Windows Phone 7 development
  • Silverlight for Windows Phone 7
  • XNA Game Studio for Windows Phone 7

Integrated with the development tools is a phone emulator that enables you to easily develop and test Windows Phone 7 applications on your laptop or desktop machine – without requiring a phone device.  It is hardware accelerated, supports multi-touch events on multi-touch capable monitors, and provides a really easy way to debug and try out your phone applications.

Devices for Developers

In addition to testing applications within the emulator, we are also this month starting to ship pre-release phones to developers.  You can learn more about this program and sign-up to receive one from this blog post from the Windows Phone 7 team.

Learning More

I previously blogged a nice step-by-step tutorial that covers how to build a Twitter search application using Visual Studio 2010 Express for Windows Phone.  It provides a nice introduction on how you can easily use Silverlight and the Visual Studio Tools for Windows Phone to quickly build applications.  You can read and follow the tutorial here.

Read today’s blog post from the Windows Phone 7 team which provides more details on today’s release. It also mentions two new Silverlight controls – a Panorama and Pivot control - which will enable you to easily implement the new Windows Phone 7 navigation style.  These controls are not implemented in today’s beta, but will be released as an update in a few weeks.

If you have used the previous Windows Phone 7 CTPs, also make sure to read Jaime’s Migrating Applications from the Windows Phone April CTP Refresh to the Beta blog post.  It provides a wealth of details on how to update code that you’ve already written.

Hope this helps,

Scott

P.S. In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu