home | non-tech | cs | ee | about
Abstract New

Entity Framework - ObjectContext vs DbContext - Accessing the ObjectContext in EF5 and above


Entity framework 4.1 introduced a feature called the DbContext - a wrapper on top of the ObjectContext. The DbContext API is simpler and easier to use. If you use database first generation a DbContext is generated by default. Infact, as a result of these API changes, migrating an Entity Framework 4.0 project to a later version will produce a bunch of errors. Using the DbContext is preferred because the API is a lot simpler. However, for people who wish to access the ObjectContext the following options are available.

Accessing the ObjectContext

A quick and easy way access the object context is by casting the DbContext object to an IObjectContextAdapter interface as shown below using System.Data.Entity.Infrastructure; ((IObjectContextAdapter)DbContextObject).ObjectContext;

Default to ObjectContext

To default to the ObjectContext when generating an entity data model via database first follow the steps below

  • Remove all the .tt files
  • Open the edmx files in the designer.
  • Click anywhere on the designer pane.
  • In the properties window you will see “code generation strategy” set to None. Change that to “Default”

No comments:

Post a Comment

© 2014 - 2015 abstract new. All rights reserved.