Entity Framework Tutorial--dbcontext

Source: Internet
Author: User

DBContext:

In the previous chapter, "Creating the Entity Data Model", the EDM created the Schooldbentities class for us, which derives the class of sub- System.Data.Entity.DbContext , This dbcontext is called the context class in EF.

Before EF4.1, the context class generated by the EDM was derived from the class ObjectContext. It's a little hard to use. DbContext is conceptually similar to ObjectContext. DbContext just encapsulates the ObjectContext to make it easier to use in all development scenarios. (such as code First, Model first, and Database first)

DbContext is an important part of EF, which is a bridge between your database and your application domain or entity class.

DbContext is the primary type responsible for interoperability of data with objects. It is primarily responsible for some of the following actions:

EntitySet: DbContext contains a collection of all the entity objects that are mapped from the database table (such as dbset<tentity>).

Querying: DbContext converts LINQ to entities into SQL query statements and sends them to the database.

Change Tracking: It keeps track of changes, and it queries from the database once the entity object has changed.

Persisting Data: It can also insert, UPDATE, and delete operations on the database based on the entity state.

Caching: DbContext defaults to a first-level cache, which stores the entity objects that were retrieved during the life cycle of the context class.

Manage Relationship: DbContext uses CSDL, MSL, and SSDL to manage relationships in Db-first or Model-first, using the streaming API to manage relationships in Code-first.

Object materialization: DbContext The original table data into the entity object.

The Schooldbentities class in the following example is another EDM created from the SCHOOLDB database

1 namespaceeftutorials2 {3     usingSystem;4     usingSystem.Data.Entity;5     usingSystem.Data.Entity.Infrastructure;6     usingSystem.Data.Entity.Core.Objects;7     usingSystem.Linq;8     9      Public Partial classSchooldbentities:dbcontextTen     { One          Publicschooldbentities () A:Base("name=schooldbentities") -         { -         } the      -         protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) -         { -             Throw Newunintentionalcodefirstexception (); +         } -      +          Public VirtualDbset<course> Courses {Get;Set; } A          Public VirtualDbset<standard> Standards {Get;Set; } at          Public VirtualDbset<student> Students {Get;Set; } -          Public VirtualDbset<studentaddress> studentaddresses {Get;Set; } -          Public VirtualDbset<teacher> Teachers {Get;Set; } -          Public VirtualDbset<view_studentcourse> View_studentcourse {Get;Set; } -      -          Public VirtualObjectresult<getcoursesbystudentid_result> Getcoursesbystudentid (nullable<int>StudentID) in         { -             varStudentidparameter = Studentid.hasvalue? to                 NewObjectParameter ("StudentID", StudentID): +                 NewObjectParameter ("StudentID",typeof(int)); -      the             return((Iobjectcontextadapter) This). Objectcontext.executefunction<getcoursesbystudentid_result> ("Getcoursesbystudentid", studentidparameter); *         } $     Panax Notoginseng          Public Virtual intSp_deletestudent (nullable<int>StudentID) -         { the             varStudentidparameter = Studentid.hasvalue? +                 NewObjectParameter ("StudentID", StudentID): A                 NewObjectParameter ("StudentID",typeof(int)); the      +             return((Iobjectcontextadapter) This). Objectcontext.executefunction ("sp_deletestudent", studentidparameter); -         } $      $          Public Virtualobjectresult<nullable<decimal>> Sp_insertstudentinfo (nullable<int> Standardid,stringstudentname) -         { -             varStandardidparameter = Standardid.hasvalue? the                 NewObjectParameter ("Standardid", Standardid): -                 New("Standardid",typeof(int));Wuyi      the             varStudentnameparameter = studentname! =NULL? -                 NewObjectParameter ("Studentname", Studentname): Wu                 NewObjectParameter ("Studentname",typeof(string)); -      About             return((Iobjectcontextadapter) This). objectcontext.executefunction<nullable<decimal>> ("Sp_insertstudentinfo", Standardidparameter, studentnameparameter); $         } -      -          Public Virtual intSp_updatestudent (nullable<int> StudentID, nullable<int> Standardid,stringstudentname) -         { A             varStudentidparameter = Studentid.hasvalue? +                 NewObjectParameter ("StudentID", StudentID): the                 NewObjectParameter ("StudentID",typeof(int)); -      $             varStandardidparameter = Standardid.hasvalue? the                 NewObjectParameter ("Standardid", Standardid): the                 NewObjectParameter ("Standardid",typeof(int)); the      the             varStudentnameparameter = studentname! =NULL? -                 NewObjectParameter ("Studentname", Studentname): in                 NewObjectParameter ("Studentname",typeof(string)); the      the             return((Iobjectcontextadapter) This). Objectcontext.executefunction ("sp_updatestudent", Studentidparameter, Standardidparameter, studentnameparameter); About         } the     } the}
View Code

You can see from the above example that the context class contains a collection of all entities of type dbset<tentity>. It also contains functions that correspond to stored procedures and views in the EDM.

The Context class overrides the Onmodelcreating method, and parameter Dbmodelbuilder provides a streaming API to configure the relationships of entities in Code-first.

Instantiate DbContext:

Instantiate DbContext to perform crud operations.

1             2 using (varnew  schooldbentities ()) 3 {4         5     // the crud operation is performed here : 6 }7      
View Code

Get ObjectContext from DbContext:

The API in DbContext in common tasks is easier to use than the ObjectContext API. Of course you can also get ObjectContext references from DbContext to use some of these methods. Can be done with Iobjectcontextadpter.

1            2 using (varnew  schooldbentities ()) 3 {4     var  as System.Data.Entity.Infrastructure.IObjectContextAdapter). ObjectContext; 5         6     // Use the ObjectContext here . 7 }8       
View Code

Entity Framework Tutorial--dbcontext

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.