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:
Why does my PortalEntities
class derive from ObjectContext
and not DbContext
as I was expecting?
Is there a major difference between ObjectContext
& DbContext
, or they are mainly the same and offer that same capabilities
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
The ObjectContext class is the primary class for interacting with data as objects that are instances of entity types that are defined in a conceptual model. An instance of the ObjectContext class encapsulates the following: A connection to the database, in the form of an EntityConnection object.
The Entity Framework is a set of technologies in ADO.NET that support the development of data-oriented software applications.
Entity framework is ORM Model, which used LINQ to access database, and code is autogenerated whereas Ado.net code is larger than Entity Framework. Ado.net is faster than Entity Framework. 1. ADO.Net is create bunch of data layer code, EF is not create.
Entity Framework API (EF6 & EF Core) includes the ability to map domain (entity) classes to the database schema, translate & execute LINQ queries to SQL, track changes occurred on entities during their lifetime, and save changes to the database.
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 ObjectContext
trough ((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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With