RememberEntity Framework 4.1/4.3 (concept)I have introduced the definitions of objectcontext objectset and dbcontext and dbset. After using 4.0 for a long time, I made a transition to 4.3. During this transition, I knew and used dbcontext and dbset. It feels good. The following table shows the objectcontext objectset dbcontext dbset:
Dbcontext API feature (dbcontext API function) |
Relevant EF4 Feature/class (related to functions/classes in EF4) |
General Purpose) |
Benefit of dbcontext API (advantages of dbcontext API) |
Dbcontext |
Objectcontext |
Represent a session with the database. Provide Query, change tracking and save capabilities (Session with database) |
Exposes and simplifies most Commonly used features of objectcontext. (Simplify common functions in objectcontext) |
Dbset |
Objectset |
Provide set operations for entity types, such as add, Attach and remove. inherits from dbquery to expose Query capabilities. (Operations on data entities such as addition, modification, and query inherit some functions of dbquery) |
Exposes and simplifies most Commonly used features of objectset. (Simplify common functions in objectset) |
Dbquery |
Objectquery |
Provide querying capabilities (Query function provided) |
The query functionality Dbquery is exposed on dbset, so You don't have to interact Dbquery directly. () |
Change Tracker API |
Objectcontext. Objectstatemanager |
Get access to change tracking information and operations (E.g., original values, current values) managed By the context. (Obtain and manage the trace information and operations (such as the original value and current value .) |
Simpler and more intuitive API Surface. (Simplify the use of more APIs) |
Validation API |
N/ |
Provide automatic validation of data at the data Layer. This API takes advantage of validation features Already existing in. Net 4. (Automated data verification is provided. The verification function already exists in. net4) |
New to dbcontext API. |
Code first Model Building |
N/ |
Reads classes and code-based deployments to build In-memory model, metadata and relevant database. (Code first) |
New to dbcontext API. |
Through the introduction in the above table, we should be able to understand the role of dbcontext dbset.
How can we use dbcontext in our project? We can use the nuget tool to obtain dbcontext. I have already introduced the nuget tool in the previous blog article (you can also check it through Baidu ). The following is a diagram showing how to use ef4.3 (that is, how to add a reference containing dbcontext ).
I. Highlights of dbcontext API
Dbcontext APIs simplify interaction between object frameworks. Compared with the previous Entity Framework (EF) version, dbcontext API reduces the number of methods and attributes. Optimized Data Query and entity Operations. Let's take a look at some examples to see how the dbcontext API is simplified and optimized. And we will make some intuitive comparison between objectcontext APIs.
(1) objectcontext example
View code
1 public class BreakAwayContext : ObjectContext 2 { 3 private ObjectSet<Person> _ people; 4 private ObjectSet<Destination> _destinations; 5 private ObjectSet<Trip> _trips; 6 public ObjectSet<Person> People 7 { 8 get { return _people ?? (_people = CreateObjectSet<Person>("People")); } 9 }10 public ObjectSet< Destination > Contacts11 {12 get { return _ destinations?? (_destinations =13 CreateObjectSet< Destination >("Destinations")); }14 }15 public ObjectSet<Trip> Trips16 {17 get { return _ trips?? (_trips = CreateObjectSet<Trip>("Trips")); }18 }19 }
The code shows a breakawaycontext class defined in EF4, which continues objectcontext. It wraps the subset into the objectsets type.
This may be a bit confusing. In my opinion, breakawaycontext is equivalent to a large container, which contains entity operation methods inherited from objectcontext. At the same time, it also contains entity subsets (in fact, corresponding tables in the database, such as student tables and teacher tables). The types of these subsets are objectset. With these subsets, in the session with the database, we can operate on it to obtain the data we want. The above code shows the application instance of objectcontext in the old version.
(2) dbcontext example
View code
1 public class BreakAwayContext : DbContext2 {3 public DbSet<Person> People { get; set; }4 public DbSet<Destination> Destinations { get; set; }5 public DbSet<Trip> Trips { get; set; }6 }
The comparison shows that dbcontext encapsulates the subset into the dbset type. Dbcontext uses code more cleanly. In dbcontext, createdbset and createobjectset have the same functions.
(3) Method Improvement
Both objectcontext and objectset provide the addobject function:
For example, context. addobject ("Students", newstudent ):
Context. Students. addobject (newstudent ):
In dbcontext, only dbset has this function and is named "add ".
Context. Students. Add (newstudent ):
The comparison shows that the add operation is an object operation, but the objectcontext and objectset both have the addobject method, which is a little inintuitive and redundant. Therefore, you can only use the add method in dbset to simplify dbcontext..
(4) Improved query of a single entity record. (That is, We query a record by ID)
Context. People. singleordefault (P => P. personid = _ personid)
This is a long-used method in the early days, but dbset provides us with a more concise method, as shown below:
Context. People. Find (_ personid)
How are you doing? Easy! However, it should be emphasized that _ personid must be the primary key. Only in this way can the find method be used.
There is another advantage: the singleordefault method will directly execute database queries, while find will first query in the cache, if not, then execute database queries. It feels good.
(5) query in dbcotext
Traverse all
private static void PrintAllDestinations(){ using (var context = new BreakAwayContext()) { foreach (var destination in context.Destinations) { Console.WriteLine(destination.Name); } }}
Sort
private static void PrintAllDestinationsSorted(){ using (var context = new BreakAwayContext()) { var query = from d in context.Destinations orderby d.Name select d; foreach (var destination in query) { Console.WriteLine(destination.Name); } }}
Local Query)
private static void GetLocalDestinationCount(){ using (var context = new BreakAwayContext()) { var count = context.Destinations.Local.Count; Console.WriteLine("Destinations in memory: {0}", count); }}
Use the load method to put data into the cache
private static void GetLocalDestinationCountWithLoad(){ using (var context = new BreakAwayContext()) { context.Destinations.Load(); var count = context.Destinations.Local.Count; Console.WriteLine("Destinations in memory: {0}", count); }}
We can also put some query results into the cache and use the load method.
private static void LoadAustralianDestinations(){ using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Country == "Australia" select d; query.Load(); var count = context.Destinations.Local.Count; Console.WriteLine("Aussie destinations in memory: {0}", count); }}
Delayed Loading
private static void TestLazyLoading(){ using (var context = new BreakAwayContext()) { var query = from d in context.Destinations where d.Name == "Grand Canyon"
select d; var canyon = query.Single(); Console.WriteLine("Grand Canyon Lodging:"); if (canyon.Lodgings != null) { foreach (var lodging in canyon.Lodgings) { Console.WriteLine(lodging.Name); } } }}
For delayed loading, I must emphasize that the usage of delayed loading must be ensured when the database connection is called. It is in using () {that objects with delayed loading can only be used in this range, because once the database connection is closed, it cannot be used. }
Pre-load (please note the include method)
private static void TestEagerLoading(){ using (var context = new BreakAwayContext()) { var allDestinations = context.Destinations.Include(d => d.Lodgings); foreach (var destination in allDestinations) { Console.WriteLine(destination.Name); foreach (var lodging in destination.Lodgings) { Console.WriteLine(" - " + lodging.Name); } } }}
Well, today I chose to write so much, and I will write dbcontext 2 later to add knowledge. It is too time-consuming to describe text, and sometimes it may lead to misunderstandings. Therefore, I mainly describe the code. I hope it will be useful to everyone. I am bailing.
Bailing Note: copyright of this ArticleBailing and the blog Park are both owned by each other. For more information, see the source.
Helping others is the same as self-help! Mbailing@163.com