Productivity Improvements for the Entity Framework

Productivity Improvements for the Entity Framework

Rate This
  • Comments 11


We’ve been hearing a lot of good feedback on the recently released update to the Entity Framework in .NET 4. This release marks a significant advancement from the first release that shipped with .NET 3.5 SP1.  I’m not going to spend time here talking about what’s new, but you can check here to see for yourself. 

With all that said, there are still a number of things we can do to simplify the process of writing data access code with the Entity Framework. We’ve been paying attention to the most common patterns that we see developers using with the EF and have been brewing up a set of improvements to the Entity Framework designed to allow developers to accomplish the same tasks with less code and fewer concepts.

These improvements provide a cleaner and simpler API surface that focuses your attention on the most common scenarios but still allows you to drill down to more advanced functionality when it’s needed.  We hope you will enjoy this simpler experience, but we should be quick to assure you that this is NOT a new data access technology.  These improvements are built on the same technology for mapping, LINQ, providers and every other part of the Entity Framework.  Think of this as a fast path to writing data access code using conventions over configuration, better tuned APIs and other techniques intended to reduce development time when using the EF.

At this stage we have worked through what we think the core API and functionality should look like and would like your feedback. There are still some capabilities such as data binding and concurrency resolution which will cause the API to evolve as we continue the design process, but the main concepts are in place, so it is a good time for feedback.

Introducing DbContext & DbSet

At the heart of the Entity Framework Productivity Improvements are two new types, DbContext and DbSet(Of TEntity). DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet(Of TEntity) is a simplified alternative to ObjectSet(Of TEntity) and is used to perform CRUD operations against a specific type from the model. These new types can be used regardless of whether you created your model using the Entity Designer or code.

The obvious question is ‘Why not just simplify ObjectContext and ObjectSet(Of T)?’  We are opting to introduce these new types in order to, on the one hand, preserve full backward compatibility with existing EF applications and continue to address all of the advanced scenarios that are possible given the EF’s existing flexibility, while on the other hand streamlining the experience of using the EF and tuning it for the most common cases.  We believe it is critical that the EF programming experience improve in some fundamental ways, and at the same time we are absolutely committed to our existing customers.  Establishing a collaborative relationship between the existing types and the new types allows us to achieve both requirements.  Also, there are easy ways to get to ObjectContext and ObjectSet(Of T) from DbContext and DbSet in case you want more control for a particular task.


One point we want to be very clear about is that these new types are not replacing any existing types; they are a simplified alternative that build on the existing types, and as we add features to the Entity Framework they will always be available in ObjectContext/ObjectSet, and they will also be available in DbContext/DbSet if appropriate.


We’ll drill into the API surface later, but first let’s take a look at the coding experience using these new types.

Code First Experience

DbContext provides a simplified Code First pattern that requires less code and takes care of some common concerns such as model caching, database provisioning, schema creation and connection management. This simplified pattern uses a number of conventions to take care of these tasks and allows tweaking or overriding of this behavior when required. Let’s start off by using these conventions to write the code needed to build a console application that performs data access using a model:

A C# version of these code samples is available here.


Imports System.Collections.Generic

Imports System.Data.Entity


Namespace MyDataAccessDemo


    Module Program


        Sub Main()


            Using context As New ProductContext()


                Dim food As New Category With {.CategoryId = "FOOD"}



                Dim cheese As New Product With {.Name = "Cheese"}

                cheese.Category = context.Categories.Find("FOOD")




            End Using


        End Sub


    End Module


    Public Class ProductContext : Inherits DbContext


        Public Property Products As DbSet(Of Product)

        Public Property Categories As DbSet(Of Category)


    End Class



    Public Class Product


        Public Property ProductId As Integer

        Public Property Name As String

        Public Property Category As Category


    End Class


    Public Class Category


        Public Property CategoryId As String

        Public Property Name As String

        Public Property Products As ICollection(Of Product)


    End Class

End Namespace



That is 100% of the code you would write to get this program running. No separate model definition, XML metadata, config file or anything else is required. Conventions are used to fill in all of this information. Obviously there is quite a bit going on under the covers so let’s take a closer look at some of the things DbContext is doing automatically.

Model Discovery

During construction we scan the derived context for DbSet properties and include the types in the model. Model Discovery uses the existing Code First functionality so the new default conventions we recently blogged about are processed during discovery. You can opt out of set discovery by specifying an attribute on the set properties that should be ignored.

Of course there will be times when you want to further describe a model or change what was detected by convention. For example say you have a Book entity whose ISBN property is the primary key, this won’t be detected by convention. There are two options here; you can use data annotations to annotate the property in your class definition:

    Public Class Book



        Public Property ISBN As String

        Public Property Title As String


    End Class



Alternatively DbContext includes a virtual method that can be overridden to use the Code First fluent API on ModelBuilder to further configure the model:


    Public Class ProductContext : Inherits DbContext


        Public Property Books As DbSet(Of Book)


        Protected Overrides Sub OnModelCreating(ByVal modelBuilder As Microsoft.Data.Objects.ModelBuilder)

            modelBuilder.Entity(Of Book)().HasKey(Function(b) b.ISBN)

        End Sub


    End Class

Model Caching

There is some cost involved in discovering the model, processing Data Annotations and applying fluent API configuration. To avoid incurring this cost every time a derived DbContext is instantiated the model is cached during the first initialization. The cached model is then re-used each time the same derived context is constructed in the same AppDomain. Model caching can be turned off by setting the CacheForContextType property on ModelBuilder to ‘false’ in the OnModelCreating method.

DbSet Initialization

You’ll notice in the sample that we didn’t assign a value to either of the DbSet properties on the derived context. During construction DbContext will scan the derived context for DbSet properties and, if they expose a public setter, will construct a new DbSet and assign it to the property. You can opt out of set initialization by specifying an attribute on the set properties that should not be initialized.

You can also create DbSet instances using the DbContext.Set(Of TEntity)() method if you don’t want to expose public setters for the DbSet properties.

Database Provisioning

By default the database is created and provisioned using SqlClient against localhost\SQLEXPRESS and has the same name as the derived context. This convention is configurable and is controlled by an AppDomain setting that can be tweaked or replaced. You can tweak the default SqlClient convention to connect to a different database, replace it with a SqlCe convention that we include or define your own convention by implementing the IDbConnectionFactory interface.



    Public Interface IDbConnectionFactory


        Function CreateConnection(ByVal databaseName As String) As DbConnection


    End Interface


The active IDbConnectionFactory can be retrieved or set via the static property, Database.DefaultConnectionFactory.


DbContext also includes a constructor that accepts a string to control the value that is passed to the convention, the SqlClient and SqlCE factories allow you to specify either a database name or the entire connection string.

Before calling the convention, DbContext will check in the app/web.config file for a connection string with the same name as your context (or the string value if you used the constructor that specifies a string). If there is a matching entry, we will use that rather than calling the convention. Because connection string entries also include provider information this allows you to target multiple providers in one application.

Finally, if you want full control over your connections there is a constructor on DbContext that accepts a DbConnection.

Database First and Model First Experience

In the latest version of the Entity Framework that shipped with .Net Framework 4.0 and Visual Studio 2010 we introduced T4 based code generation. T4 allows you to customize the code that is generated based on a model you have defined using the designer in either the Database First or Model First approach. The default template generates a derived ObjectContext with an ObjectSet(Of T) for each entity set in your model.

The productivity improvements will also include a template that generates a derived DbContext with a DbSet(Of TEntity) for each entity set in your model. This allows Model First and Database First developers to make use of the simplified API surface described in the next section.

API Surface

DbContext is the starting point for interacting with your model. Compared to ObjectContext it has a greatly reduced number of methods and properties that are exposed at the root level. The aim is to expose only the most commonly used methods on DbContext and have the ability to drill down to more advanced APIs. One example of this is the Database property that exposes database related APIs. We will add a couple more members as we work through adding the rest of the advanced functionality but we want to keep it as minimal as possible. In most cases you would work with a context that derives from DbContext and exposes strongly typed DbSet properties for the types in your model.


    Public Class DbContext : Implements IDisposable


        Public Sub New(ByVal model As DbModel, ByVal nameOrConnectionString As String)

        Public Sub New(ByVal model As DbModel, ByVal existingConnection As DbConnection)

        Public Sub New(ByVal objectContext As ObjectContext)


        Protected Sub New()

        Protected Sub New(ByVal nameOrConnectionString As String)

        Protected Sub New(ByVal existingConnection As DbConnection)


        Public ReadOnly Property Database As Database

        Protected ReadOnly Property ObjectContext As ObjectContext


        Protected Overridable Sub OnModelCreating(ByVal modelBuilder As ModelBuilder)

        Public Overridable Function SaveChanges() As Integer


        Public Function [Set](Of TEntity As Class)() As DbSet(Of TEntity)

        Public Sub Dispose() Implements IDisposable.Dispose


    End Class


DbModel Constructors

These constructors can be used with Database First, Model First and Code First development. They are used by our T4 template for Database First and Model First Development and can also be used in Code First scenarios where a model is built externally using ModelBuilder.

Code First previously contained a ContextBuilder type which we have now split into two components, ModelBuilder and DbModel. ModelBuilder is mutable and exposes the fluent API for defining your model. ModelBuilder creates an immutable DbModel type that can be used to construct an ObjectContext or DbContext. DbModel can also be constructed from a Database First or Model First approach where an edmx file is generated.

ObjectContext Constructor

If you have an existing code base that uses ObjectContext and want to make use of the alternate surface of DbContext in some parts of your code then this constructor allows you to wrap the ObjectContext with the simpler surface.

Protected Constructors

The three protected constructors can be exposed or used within a derived context where you want to make use of the simplified Code First experience which was explained in the ‘Code First Experience’ section. They are protected because the model discovery, database provisioning and model caching mechanisms rely on having a derived context.


The Database property exposes an instance of the new Database type that contains methods for interacting with the underlying database.


    Public Class Database

        Public ReadOnly Property Connection() As DbConnection


        Public Sub Create()

        Public Function CreateIfNotExists() As Boolean


        Public Function Exists() As Boolean

        Public Shared Function Exists(nameOrConnectionString As String) As Boolean

        Public Shared Function Exists(existingConnection As DbConnection) As Boolean


        Public Sub Delete()

        Public Shared Sub Delete(ByVal nameOrConnectionString As String)

        Public Shared Sub Delete(ByVal existingConnection As DbConnection)


        Public Function DeleteIfExists() As Boolean

        Public Shared Function DeleteIfExists(nameOrConnectionString As String) As Boolean

        Public Shared Function DeleteIfExists(existingConnection As DbConnection) As Boolean


    End Class



DbContext uses an ObjectContext internally and we make this available as a protected property just in case you ever need to drop down to the lower level API. You can use or expose the required functionality from a derived DbContext.


This protected member can be overridden when defining a derived context in CodeFirst development and allows you tweak the shape of your model that was detected by convention.


This method exposes the same functionality as SaveChanges on ObjectContext and persists all pending changes to the database. It represents the Unit of Work for the context.

Set(Of TEntity)

This method will create a DbSet(Of TEntity) for an entity type that is part of your model, similar to CreateObjectSet(Of T) on ObjectContext.

DbSet represents a collection of a given entity type in your model, similar to ObjectSet(Of T) except that this new type also supports derived types whereas ObjectSet(Of T) only supported base types.


    Public Class DbSet(Of TEntity As Class) : Implements IDbSet(Of TEntity), IQueryable(Of TEntity)


        Public Sub Add(ByVal entity As TEntity) Implements IDbSet(Of TEntity).Add


        Public Sub Remove(ByVal entity As TEntity) Implements IDbSet(Of TEntity).Remove


        Public Sub Attach(ByVal entity As TEntity) Implements IDbSet(Of TEntity).Attach


        Public Function Find(ByVal ParamArray keyValues As Object()) As TEntity Implements IDbSet(Of TEntity).Find


    End Class


Add, Remove & Attach

Add, Remove and Attach are similar to AddObject, DeleteObject and Attach on ObjectSet(Of T). We’ve renamed Add and Remove to keep DbSet(Of TEntity) consistent with other sets in the framework.

Add and Attach can now be called on objects that are already tracked by the context, Add will ensure the object is in the added state and Attach the unchanged state. This is helpful in N-Tier and Web scenarios where you have a detached graph containing both existing and new entities that need to be hooked up to the context.

For example assume you have a new product that is linked to an existing category, neither instance is attached to a context (they may have been returned from a distributed client via a web service call or built from a post back in a web application). Because Add and Attach are graph operations, calling Add on the product will also Add the category. Previously you would need to drop down to lower level APIs (ObjectStateManager.ChangeObjectState) to mark the category as unchanged. Now however this can be achieved by calling Attach:


    Public Sub AddProduct(ByVal product As Product)


        Using context = New ProductContext()






        End Using


    End Sub



The new Find method will locate an object with the supplied primary key value(s). Find initially checks the in-memory objects before querying the database and is capable of finding added entities that haven’t been persisted to the store yet. If find doesn’t locate an entity with the matching key it returns null.

IDbSet(Of TEntity)

DbSet(Of TEntity) implements IDbSet(Of TEntity) to facilitate building testable applications.


    Public Interface IDbSet(Of TEntity As Class) : Inherits IQueryable(Of TEntity)


        Sub Add(ByVal entity As TEntity)

        Sub Attach(ByVal entity As TEntity)

        Sub Remove(ByVal entity As TEntity)

        Function Find(ByVal ParamArray keyValues As Object()) As TEntity


    End Interface


IDbSet(Of TEntity) allows you to define an interface that can be implemented by your derived context, similar to the example shown below. This allows the context to be replaced with an in-memory test double for testing. DbContext will still perform set discovery and initialization, described in the ‘Code First Development’ section, for properties typed as IDbSet(Of TEntity).


    Public Interface IProductContext


        ReadOnly Property Products() As IDbSet(Of Product)

        ReadOnly Property Categories() As IDbSet(Of Category)


    End Interface


    Public Class ProductContext : Inherits DbContext : Implements IProductContext


        Public Property Products() As IDbSet(Of Product) Implements IProductContext.Products

        Public Property Categories() As IDbSet(Of Category) Implements IProductContext.Categories


    End Class


These improvements are designed to provide a cleaner and simpler API surface that allows you to achieve common scenarios with ease while also allowing you to drill down to more advanced functionality when required. The improvements build on top of the existing Entity Framework components using conventions over configuration and a simplified API surface.

We’d like to hear any feedback you have on the proposed functionality and API surface.

Rowan Miller
Program Manager
ADO.NET Entity Framework Team


Leave a Comment
  • Please add 3 and 3 and type the answer here:
  • Post
  • If you're trying to increase the credibility of the Entity Framework, or otherwise improve overall impressions of it in its market (which is not without significant competitors), your examples should be in C#.  This VB.NET stuff is going to be laughed at.  Please don't interpret my comment as arrogant or fan boish.  It's not necessarily a reflection of my own opinion, I'm simply stating how people are going to react, generally.

  • Sam,

    as mentioned in the post, samples are provided in C# also:

  • Rowan,

    Thank you for the article and especially for the VB code examples. No laughing here.

    It is a real sign of professionalism when an author takes the time to provide examples in both C# and VB. Well done.


  • @ Sam

    With the way is growing and also from <a href=" blog entry,  I would not scoff at VB.  It is a very powerful language and it is extremely fast to develop in.!=vb6  or for the vb'ers here<>vb6.  Just because you think it is a piddly language does not make it so.  Write a real program in once you learn the language.  You may not like the language but I don't think you need to act all uppity just because you write in C#.  Because of the way that .net compiles into MSIL, and C# are first class languages.  You no longer have the vb runtime.  I can write a program in and c# and get similar MSIL.

  • Aside to excellent additions to EF , I want to thank MS for recognizing VB again as an important language and start sampling with it to us in professional articles , after many years of C# only samples , please continue the trend.

  • Sam, I think your comment is one of the most bizarre I have ever read. You would have to be a bigoted idiot to laugh at a coding example because it wasn't written in your language of choice.

  • My suggestions for improvement of EF.

    Create property to inform you that the field is an index. It should not reflect on the bench as the primary key, and yes, as an index.

    By creating a relationship between the classes ERROR LIST is telling me of a possible error.

    When I create a COMPLEX TYPE and inform the same in a propeidade, the attribute name in the database always stays with the property name + the name of the complex type.

    Congratulations to Team EF, and how to comment on the VB: Visual Basic is what time does not have to prove anything after all he is the father and grandfather 20 years of existence and a lot of maturity.

  • VB.Net is an awesome language.  Please continue to show samples in a matter of fact, I would like to see more examples in VB.

  • Indeed, kudos for using code examples. As for gripes about C# samples, for crying out loud, this is the VB TEAM BLOG! It' speaks volumes that they'd include C# samples here when such a large proportion of the C# samples out there +do not+ include VB versions.

    Why anyone would read +this+ blog, then bother to gripe about no C# samples is beyond me.

    EF looks pretty interesting, but I'm a little hesitant, given that there doesn't seem to be a lot of support for backends other than MSSQL. Understandable, but in the commercial apps I tend to write, I have to have the flexibility to connect to a variety of backends. I'll be doing some more research into that.

  • how can i count a mark image using VB6?

  • Please add an example of using the DbContext with an IDbSet and causing the initialization in code.

    I am trying to get mock unit testing going and I cannot get the DbContext initialized properly.  

    This does not work:

    Mock<PosManContext> posManContext;

    posManContext = new Mock<PosManContext>();



     new note_template()


        note_template_id = 1,

         act_flag = "Y",

         desc_text = "Monday Monday",

         last_update_dtm = now,

         last_update_user_id = "hsimpson",


    The Add fails because the DbSet is null.

    Help me get the DbSet created in code.

    Thanks, Joe

Page 1 of 1 (11 items)