<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://weblogs.asp.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Jon Galloway : Entity Framework</title><link>http://weblogs.asp.net/jgalloway/archive/tags/Entity+Framework/default.aspx</link><description>Tags: Entity Framework</description><dc:language>en</dc:language><generator>CommunityServer 2007 SP1 (Build: 20510.895)</generator><item><title>Generating EF Code First model classes from an existing database</title><link>http://weblogs.asp.net/jgalloway/archive/2011/02/24/generating-ef-code-first-model-classes-from-an-existing-database.aspx</link><pubDate>Thu, 24 Feb 2011 21:25:11 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:7712167</guid><dc:creator>Jon Galloway</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/jgalloway/rsscomments.aspx?PostID=7712167</wfw:commentRss><comments>http://weblogs.asp.net/jgalloway/archive/2011/02/24/generating-ef-code-first-model-classes-from-an-existing-database.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx"&gt;Entity Framework Code First&lt;/a&gt; is a lightweight way to &amp;quot;turn on&amp;quot; data access for a simple CLR class. As the name implies, the intended use is that you're writing the code first and thinking about the database later.&lt;/p&gt;  &lt;p&gt;However, I really like the Entity Framework Code First works, and I want to use it in existing projects and projects with pre-existing databases. For example, MVC Music Store comes with a SQL Express database that's pre-loaded with a catalog of music (including genres, artists, and songs), and while it may eventually make sense to load that seed data from a different source, for the MVC 3 release we wanted to keep using the existing database. While I'm not getting the full benefit of Code First - writing code which drives the database schema - I can still benefit from the simplicity of the lightweight code approach.&lt;/p&gt;  &lt;p&gt;Scott Guthrie blogged about &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx"&gt;how to use entity framework with an existing database&lt;/a&gt;, looking at how you can override the Entity Framework Code First conventions so that it can work with a database which was created following other conventions. That gives you the information you need to create the model classes manually. However, it turns out that with Entity Framework 4 CTP 5, there's a way to generate the model classes from the database schema. Once the grunt work is done, of course, you can go in and modify the model classes as you'd like, but you can save the time and frustration of figuring out things like mapping SQL database types to .NET types.&lt;/p&gt;  &lt;p&gt;Note that this template requires Entity Framework 4 CTP 5 or later. You can &lt;a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=35adb688-f8a7-4d28-86b1-b6235385389d"&gt;install EF 4 CTP 5 here&lt;/a&gt;.&lt;/p&gt;  &lt;h2&gt;Step One: Generate an EF Model from your existing database&lt;/h2&gt;  &lt;p&gt;The code generation system in Entity Framework works from a model. You can add a model to your existing project and delete it when you're done, but I think it's simpler to just spin up a separate project to generate the model classes. When you're done, you can delete the project without affecting your application, or you may choose to keep it around in case you have other database schema updates which require model changes.&lt;/p&gt;  &lt;p&gt;I chose to add the Model classes to the Models folder of a new MVC 3 application. Right-click the folder and select &amp;quot;Add / New Item...&amp;quot;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472671316/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5094/5472671316_b6b21f9d18_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Next, select ADO.NET Entity Data Model from the Data Templates list, and name it whatever you want (the name is unimportant).&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472079693/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5137/5472079693_3b3848cbc4_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Next, select &amp;quot;Generate from database.&amp;quot; This is important - it's what kicks off the next few steps, which read your database's schema.&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472671346/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5091/5472671346_175f5138b8_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Now it's time to point the Entity Data Model Wizard at your existing database. I'll assume you know how to find your database - if not, I covered that a bit in the &lt;a href="http://www.asp.net/mvc/tutorials/mvc-music-store-part-4"&gt;MVC Music Store tutorial section on Models and Data&lt;/a&gt;. Select your database, uncheck the &amp;quot;Save entity connection settings in Web.config&amp;quot; (since we won't be using them within the application), and click Next.&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472671458/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5216/5472671458_1c4d0b488c_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Now you can select the database objects you'd like modeled. I just selected all tables and clicked Finish.&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472671488/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5100/5472671488_391c358509_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;And there's your model. If you want, you can make additional changes here before going on to generate the code.&lt;/p&gt;  &lt;p&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5214/5472671580_c2539a77bc_b.jpg" /&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h2&gt;Step Two: Add the DbContext Generator&lt;/h2&gt;  &lt;p&gt;Like most code generation systems in Visual Studio lately, Entity Framework uses T4 templates which allow for some control over how the code is generated. K Scott Allen wrote a detailed article on &lt;a href="http://msdn.microsoft.com/en-us/gg558520"&gt;T4 Templates and the Entity Framework on MSDN recently&lt;/a&gt;, if you'd like to know more. Fortunately for us, there's already a template that does just what we need without any customization.&lt;/p&gt;  &lt;p&gt;Right-click a blank space in the Entity Framework model surface and select &amp;quot;Add Code Generation Item...&amp;quot;&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472671586/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5099/5472671586_e9270b077a_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Select the Code groupt in the Installed Templates section and pick the ADO.NET DbContext Generator. If you don't see this listed, make sure you've got EF 4 CTP 5 installed and that you're looking at the Code templates group. Note that the DbContext Generator template is similar to the &lt;a href="http://blogs.msdn.com/b/adonet/archive/2010/01/25/walkthrough-poco-template-for-the-entity-framework.aspx"&gt;EF POCO template&lt;/a&gt; which came out last year, but with &amp;quot;fix up&amp;quot; code (unnecessary in EF Code First) removed.&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472079981/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5100/5472079981_8e1600ccef_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;As soon as you do this, you'll two terrifying Security Warnings - unless you click the &amp;quot;Do not show this message again&amp;quot; checkbox the first time. It will also be displayed (twice) every time you rebuild the project, so I checked the box and no immediate harm befell my computer (fingers crossed!).&lt;/p&gt;  &lt;p&gt;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472079997/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5092/5472079997_82d1ae3130_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Here's the payoff: two templates (filenames ending with .tt) have been added to the project, and they've generated the code I needed. &lt;/p&gt;  &lt;p&gt;&lt;/a&gt;&amp;#160;&lt;a title="EF Code First Models from an existing database" href="http://www.flickr.com/photos/36836555@N00/5472080009/"&gt;&lt;img border="0" alt="EF Code First Models from an existing database" src="http://static.flickr.com/5014/5472080009_162cd16243_b.jpg" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The &amp;quot;MusicStoreEntities.Context.tt&amp;quot; template built a DbContext class which holds the entity collections, and the &amp;quot;MusicStoreEntities.tt&amp;quot; template build a separate class for each table I selected earlier. We'll customize them in the next step.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;I recommend copying all the generated .cs files into your application at this point, since accidentally rebuilding the generation project will overwrite your changes if you leave them there.&lt;/strong&gt;&lt;/p&gt;  &lt;h2&gt;Step Three: Modify and use your POCO entity classes&lt;/h2&gt;  &lt;p&gt;&lt;em&gt;Note: I made a bunch of tweaks to my POCO classes after they were generated. You don't have to do any of this, but I think it's important that you can - they're &lt;strong&gt;your&lt;/strong&gt; classes, and EF Code First respects that. Modify them as you need for your application, or don't.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;The Context class derives from DbContext, which is what turns on the EF Code First features. It holds a DbSet for each entity. Think of DbSet as a simple List, but with Entity Framework features turned on. &lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;pre class="brush: csharp; auto-links: false;"&gt;//------------------------------------------------------------------------------
// &amp;lt;auto-generated&amp;gt;
//     This code was generated from a template.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// &amp;lt;/auto-generated&amp;gt;
//------------------------------------------------------------------------------

namespace EF_CodeFirst_From_Existing_Database.Models
{
    using System;
    using System.Data.Entity;
    
    public partial class Entities : DbContext
    {
        public Entities()
            : base(&amp;quot;name=Entities&amp;quot;)
        {
        }
    
        public DbSet&amp;lt;Album&amp;gt; Albums { get; set; }
        public DbSet&amp;lt;Artist&amp;gt; Artists { get; set; }
        public DbSet&amp;lt;Cart&amp;gt; Carts { get; set; }
        public DbSet&amp;lt;Genre&amp;gt; Genres { get; set; }
        public DbSet&amp;lt;OrderDetail&amp;gt; OrderDetails { get; set; }
        public DbSet&amp;lt;Order&amp;gt; Orders { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;It's a pretty lightweight class as generated, so I just took out the comments, set the namespace, removed the constructor, and formatted it a bit. Done.&lt;/p&gt;

&lt;p&gt;If I wanted, though, I could have added or removed DbSets, overridden conventions, etc.&lt;/p&gt;

&lt;pre class="brush: csharp; auto-links: false;"&gt;using System.Data.Entity;

namespace MvcMusicStore.Models
{
    public class MusicStoreEntities : DbContext
    {
        public DbSet&lt;album&gt;     Albums  { get; set; }
        public DbSet&lt;genre&gt;     Genres  { get; set; }
        public DbSet&lt;artist&gt;    Artists { get; set; }
        public DbSet&lt;cart&gt;      Carts { get; set; }
        public DbSet&lt;order&gt;     Orders { get; set; }
        public DbSet&lt;orderdetail&gt; OrderDetails { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;Next, it's time to look at the individual classes. Some of mine were pretty simple - for the Cart class, I just need to remove the header and clean up the namespace.&lt;/p&gt;

&lt;pre class="brush: csharp; auto-links: false;"&gt;//------------------------------------------------------------------------------
// &lt;auto-generated&gt;
//     This code was generated from a template.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// &lt;/auto-generated&gt;
//------------------------------------------------------------------------------

namespace EF_CodeFirst_From_Existing_Database.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Cart
    {
        // Primitive properties
    
        public int RecordId { get; set; }
        public string CartId { get; set; }
        public int AlbumId { get; set; }
        public int Count { get; set; }
        public System.DateTime DateCreated { get; set; }
    
        // Navigation properties
    
        public virtual Album Album { get; set; }
    
    }
}&lt;/pre&gt;

&lt;p&gt;I did a bit more customization on the Album class. Here's what was generated:&lt;/p&gt;

&lt;pre class="brush: csharp; auto-links: false;"&gt;//------------------------------------------------------------------------------
// &lt;auto-generated&gt;
//     This code was generated from a template.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// &lt;/auto-generated&gt;
//------------------------------------------------------------------------------

namespace EF_CodeFirst_From_Existing_Database.Models
{
    using System;
    using System.Collections.Generic;
    
    public partial class Album
    {
        public Album()
        {
            this.Carts = new HashSet&lt;cart&gt;();
            this.OrderDetails = new HashSet&lt;orderdetail&gt;();
        }
    
        // Primitive properties
    
        public int AlbumId { get; set; }
        public int GenreId { get; set; }
        public int ArtistId { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public string AlbumArtUrl { get; set; }
    
        // Navigation properties
    
        public virtual Artist Artist { get; set; }
        public virtual Genre Genre { get; set; }
        public virtual ICollection&lt;cart&gt; Carts { get; set; }
        public virtual ICollection&lt;orderdetail&gt; OrderDetails { get; set; }
    
    }
}&lt;/pre&gt;

&lt;p&gt;I removed the header, changed the namespace, and removed some of the navigation properties. One nice thing about EF Code First is that you don't have to have a property for each database column or foreign key. In the Music Store sample, for instance, we build the app up using code first and start with just a few columns, adding in fields and navigation properties as the application needs them. EF Code First handles the columsn we've told it about and doesn't complain about the others. Here's the basic class:&lt;/p&gt;

&lt;pre class="brush: csharp; auto-links: false;"&gt;using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;
namespace MvcMusicStore.Models
{
    public class Album
    {
        public int      AlbumId    { get; set; }
        public int      GenreId    { get; set; }
        public int      ArtistId   { get; set; }
        public string   Title      { get; set; }
        public decimal Price       { get; set; }
        public string AlbumArtUrl  { get; set; }
        public virtual Genre  Genre                     { get; set; }
        public virtual Artist Artist                    { get; set; }
        public virtual List&lt;orderdetail&gt; OrderDetails   { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;It's my class, not Entity Framework's, so I'm free to do what I want with it. I added a bunch of MVC 3 annotations for scaffolding and validation support, as shown below:&lt;/p&gt;

&lt;pre class="brush: csharp; auto-links: false;"&gt;using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;

namespace MvcMusicStore.Models
{
    [Bind(Exclude = &amp;quot;AlbumId&amp;quot;)]
    public class Album
    {
        [ScaffoldColumn(false)]
        public int      AlbumId    { get; set; }

        [DisplayName(&amp;quot;Genre&amp;quot;)]
        public int      GenreId    { get; set; }

        [DisplayName(&amp;quot;Artist&amp;quot;)]
        public int      ArtistId   { get; set; }

        [Required(ErrorMessage = &amp;quot;An Album Title is required&amp;quot;)]
        [StringLength(160)]
        public string   Title      { get; set; }

        [Required(ErrorMessage = &amp;quot;Price is required&amp;quot;)]
        [Range(0.01, 100.00,
            ErrorMessage = &amp;quot;Price must be between 0.01 and 100.00&amp;quot;)]
        public decimal Price       { get; set; }

        [DisplayName(&amp;quot;Album Art URL&amp;quot;)]
        [StringLength(1024)]
        public string AlbumArtUrl { get; set; }

        public virtual Genre  Genre                     { get; set; }
        public virtual Artist Artist                    { get; set; }
        public virtual List&amp;lt;OrderDetail&amp;gt; OrderDetails   { get; set; }
    }
}&lt;/pre&gt;

&lt;p&gt;The end result was that I had working EF Code First model code for the finished application. You can follow along through the tutorial to see how I built up to the finished model classes, &lt;a href="http://www.asp.net/mvc/tutorials/mvc-music-store-part-4"&gt;starting with simple 2-3 property classes&lt;/a&gt; and &lt;a href="http://www.asp.net/mvc/tutorials/mvc-music-store-part-5"&gt;building up&lt;/a&gt; to the &lt;a href="http://www.asp.net/mvc/tutorials/mvc-music-store-part-10"&gt;full working schema&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Thanks to &lt;/em&gt;&lt;a href="http://blogs.msdn.com/b/diego/"&gt;&lt;em&gt;Diego Vega&lt;/em&gt;&lt;/a&gt;&lt;em&gt; (on the Entity Framework team) for pointing me to the DbContext template.&lt;/em&gt;&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7712167" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/jgalloway/archive/tags/.NET+code/default.aspx">.NET code</category><category domain="http://weblogs.asp.net/jgalloway/archive/tags/.NET/default.aspx">.NET</category><category domain="http://weblogs.asp.net/jgalloway/archive/tags/Visual+Studio/default.aspx">Visual Studio</category><category domain="http://weblogs.asp.net/jgalloway/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item><item><title>FIX: WCF Data Service with Entity Framework Code-First DbContext doesn’t accept updates</title><link>http://weblogs.asp.net/jgalloway/archive/2011/01/21/fix-wcf-data-service-with-entity-framework-code-first-dbcontext-doesn-t-accept-updates.aspx</link><pubDate>Fri, 21 Jan 2011 18:40:03 GMT</pubDate><guid isPermaLink="false">c06e2b9d-981a-45b4-a55f-ab0d8bbfdc1c:7687425</guid><dc:creator>Jon Galloway</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://weblogs.asp.net/jgalloway/rsscomments.aspx?PostID=7687425</wfw:commentRss><comments>http://weblogs.asp.net/jgalloway/archive/2011/01/21/fix-wcf-data-service-with-entity-framework-code-first-dbcontext-doesn-t-accept-updates.aspx#comments</comments><description>&lt;h3&gt;Summary&lt;/h3&gt;  &lt;p&gt;The Entity Framework Code First DbContext doesn’t expose the interfaces to support updates when exposed via WCF Data Services. Attempting to save changes results in a fault with the message &amp;quot;The data source must implement IUpdatable or IDataServiceUpdateProvider to support updates.&amp;quot; The fix is to alter your WCF Data Service to expose the DbContext's underlying ObjectContext and to disable proxy generation.&lt;/p&gt;  &lt;h3&gt;Background&lt;/h3&gt;  &lt;p&gt;Jesse Liberty and I have stumbled into some frontier country. Our work on a Windows Phone + WCF Data Services + EF Code First + MVC 3 solution for the The Full Stack has put us in that delightful developer place where the combination of two or more pre-release or newly-released bits can feel like you're in primordial-ooze-technical-preview stage. Honestly, it's our job to get there before you do, and we love it.&lt;/p&gt;  &lt;p&gt;I've been pushing Entity Framework Code-First to anyone who will listen. My kids are sick of hearing about it... &amp;quot;yes, dad, POCO object, no config, we GET it!&amp;quot;&lt;/p&gt;  &lt;p&gt;We'd figured out how to connect all the pieces together so that data in an ASP.NET MVC 3 using SQL CE and EF Code First could expose data to a Windows Phone client via a WCF Data Service. That sounds like a lot of moving parts, but it actually went pretty smoothly once we figured out the steps, as documented &lt;a href="http://weblogs.asp.net/jgalloway/archive/2011/01/06/entity-framework-code-first-odata-amp-windows-phone-client.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;h3&gt;The problem - the service was read-only&lt;/h3&gt;  &lt;p&gt;Our goal is to build out a contact manager application that allows you to quickly store and look up contacts by description, e.g. short, long hair, works for Microsoft, met at MIX 2010.&lt;/p&gt;  &lt;p&gt;Our phone client did a fine job of reading the data from the service, but our attempts to save changes back to the service gave some errors that were hard to troubleshoot. Based on some help from &lt;a href="http://twitter.com/cwoodruff" target="_blank"&gt;Chris &amp;quot;Woody&amp;quot; Woodruff&lt;/a&gt;, we changed our update method to stop using batching, and we started seeing the specific error message: &amp;quot;The data source must implement IUpdatable or IDataServiceUpdateProvider to support updates.&amp;quot;&lt;/p&gt;  &lt;p&gt;That error message led me to a comment on &lt;a href="http://romiller.com/2010/07/19/ef-ctp4-tips-tricks-wcf-data-service-on-dbcontext/" target="_blank"&gt;a post by Rowan Miller on using WCF Data Services against a DbContext&lt;/a&gt;, which is exactly what we were doing. Rowan points out that if you're going by experience or documentation on using Entity Framework (before Code First), you'd create a simple WCF Data Service and point it at your Context class, and everything would work. However:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Now what if your BlogContext derives from DbContext instead of ObjectContext? In the current CTP4 you can’t just create a DataService of a derived DbContext, although you can expect this to work by the time there is an RTM release.&lt;/p&gt;    &lt;p&gt;But there is some good news, DbContext uses ObjectContext under the covers and you can get to the underlying context via a protected member.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;&lt;em&gt;Aha, you say - that was for CTP4, and there's a newer release. Read on...&lt;/em&gt;&lt;/p&gt;  &lt;h3&gt;DbContext as a lightweight, convention-based wrapper over ObjectContext&lt;/h3&gt;  &lt;p&gt;DbContext is really easy to work with. It does the basic things you'd expect from ObjectContext, like tracking changes to your entities, batching changes, etc. The &lt;a href="http://blogs.msdn.com/b/adonet/archive/2010/09/02/ef-feature-ctp4-dbcontext-and-databases.aspx" target="_blank"&gt;DbContext also adds some other convention-based goodness on top, though, which does things like infer what the database connection should be based on the the entity name, creating the database if it doesn't exist, etc.&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;However, the DbContext abstracts away / hides some capabilities in the ObjectContext. Usually, those capabilities aren't things you'll miss, but occasionally you will. In this case, we need IUpdatable support, as the &lt;a href="http://msdn.microsoft.com/en-us/library/cc646779.aspx" target="_blank"&gt;MSDN documentation for DataService&amp;lt;T&amp;gt;&lt;/a&gt; explains:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;The type of the DataService&amp;lt;T&amp;gt; must expose at least one property that returns an entity set that is an &lt;a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx"&gt;IQueryable&amp;lt;T&amp;gt;&lt;/a&gt; collection of entity types. This class must also implement the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.services.iupdatable.aspx"&gt;IUpdatable&lt;/a&gt; interface to enable updates to be made to entity resources.&lt;/p&gt; &lt;/blockquote&gt;  &lt;h3&gt;The workaround - Expose the DbContext's base ObjectContext&lt;/h3&gt;  &lt;p&gt;Rowan Miller explains the workaround, which involves two short steps. Fortunately, since he posted that info (valid for CTP4), it's become even easier, since DbContext directly exposes the ObjectContext with your having to write a property to expose it. Prior to EF Code First CTP 5, if you wanted to call into the base ObjectContext, you had to expose the underlying context via a property, like this:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;public class BlogContext : DbContext
{
    public DbSet&amp;lt;Blog&amp;gt; Blogs { get; set; }
    public DbSet&amp;lt;Post&amp;gt; Posts { get; set; }

    public ObjectContext UnderlyingContext
    {
        get { return this.ObjectContext; }
    }
}&lt;/pre&gt;

&lt;p&gt;In CTP5, the DbContext implements IObjectContextAdapter, which exposes the ObjectContext. So, putting that together, if you want to set up a WCF Data Service that exposes a DbContext named PersonContext, you’ll need to change from this:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;public class PersonTestDataService : DataService&amp;lt;PersonContext&amp;gt;
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule(&amp;quot;*&amp;quot;, EntitySetRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }
}&lt;/pre&gt;

&lt;p&gt;to this:&lt;/p&gt;

&lt;pre class="brush: csharp; auto-links: false;"&gt;public class PersonTestDataService : DataService&amp;lt;ObjectContext&amp;gt;
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule(&amp;quot;*&amp;quot;, EntitySetRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }

    protected override ObjectContext CreateDataSource()
    {
        var ctx = new PersonContext();
        var objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
        objectContext.ContextOptions.ProxyCreationEnabled = false;
        return objectContext;
    }
}&lt;/pre&gt;

&lt;p&gt;Here’s the summary of what we did:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The DataService is typed as ObjectContext rather than the class which implemented DbContext (PersonContext). &lt;/li&gt;

  &lt;li&gt;We override CreateDataSource to get at the PersonContxt’s underlying ObjectContext, returning the ObjectContext as the result. &lt;/li&gt;

  &lt;li&gt;We disable Proxy Creation, which apparently does something magical. I just got it from Rowan Miller’s post and it works, so I’m not going to complain. &lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Updating the client proxy&lt;/h3&gt;

&lt;p&gt;If you’d previously created a client service proxy (via DataSvcUtil) for the service, you’ll need to regenerate it because the ObjectContext based WCF Service now implements IUpdatable and thus exposes some new additional methods. In our test case - a flat object model with one class holding simple strings - the changes to the client proxy class were to set up property change notifications:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged;&lt;/li&gt;

  &lt;li&gt;protected virtual void OnPropertyChanged(string property)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;Fun with IObjectContextAdapter&lt;/h3&gt;

&lt;p&gt;I’ve run into other circumstances where I needed access to the DbContext’s ObjectContext – for instance working with the ObjectStateManager. It’s nice to be able to cast a DbContext to an IObjectContextAdapter to get at the ObjectContext, then go to town with the base ObjectContext.&lt;/p&gt;&lt;img src="http://weblogs.asp.net/aggbug.aspx?PostID=7687425" width="1" height="1"&gt;</description><category domain="http://weblogs.asp.net/jgalloway/archive/tags/Fix/default.aspx">Fix</category><category domain="http://weblogs.asp.net/jgalloway/archive/tags/.NET/default.aspx">.NET</category><category domain="http://weblogs.asp.net/jgalloway/archive/tags/Entity+Framework/default.aspx">Entity Framework</category></item></channel></rss>