12

I am following the database approach first; I have created the tables in my SQL Server 2008 database, then I map those tables to Entity Framework classes using an ADO.NET Entity Data Model. But when I opened the designer.cs file I found the following code in the class definition which was created automatically:

public partial class PortalEntities : ObjectContext

so I have the following three question that get my confused:

  1. Why does my PortalEntities class derive from ObjectContext and not DbContext as I was expecting?

  2. Is there a major difference between ObjectContext & DbContext, or they are mainly the same and offer that same capabilities

  3. When I try to write the something similar to the following code:

    Student student = db.Students.Find(id);
    

I found that I cannot use .Find() method as I used to do using DbContext, so does this mean that ObjectContext & DbContext have different methods that I can use?

BR

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John John
  • 1
  • 72
  • 238
  • 501

2 Answers2

23

The DbContext is a wrapper around the ObjectContext which simplifies the interface for the things we do most.

If you have an DbContext you can still access the ObjectContexttrough ((IObjectContextAdapter)dbContext).ObjectContext;

If you want to use the DbContext instead of the ObjectContext when using database first, you can switch the template that's used for generating your code. You can do this by right-clicking in your EDMX and selecting 'Add Code Generation Item'. You can then select the DbContext template.

Here is an example of the whole process.

Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
  • thanks for your reply; but will i benefit from using DbContext instead of ObjectContext in my database apprach first ?. – John John Jan 26 '12 at 18:10
  • 4
    The DbContext has a simplified interface. It will be easier to use and if necessary you can always cast it to an ObjectContext. Also the DbContext is easier to mock for unit testing purposes. – Wouter de Kort Jan 26 '12 at 19:26
0

Since VS2012 the default code generation changed from ObjectContext to DbContext.

Timeless
  • 7,338
  • 9
  • 60
  • 94