博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
DBContext
阅读量:4347 次
发布时间:2019-06-07

本文共 5870 字,大约阅读时间需要 19 分钟。

As you have seen in the previous  section, EDM generates the SchoolDBEntities class, which was derived from theSystem.Data.Entity.DbContext class, as shown below.

The class that derives DbContext is called context class in entity framework.

Prior to EntityFramework 4.1, EDM used to generate context classes that were derived from the ObjectContext class.

It was a little tricky to work with ObjectContext. DbContext is conceptually similar to ObjectContext.

It is a wrapper around ObjectContext which is useful in all the development models: Code First, Model First and Database First.

 

DbContext is an important part of Entity Framework.

It is a bridge between your domain or entity classes and the database.

 

 

DbContext is the primary class that is responsible for interacting with data as object.

DbContext is responsible for the following activities:

  • EntitySet: DbContext contains entity set (DbSet<TEntity>) for all the entities which is mapped to DB tables.
  • Querying: DbContext converts LINQ-to-Entities queries to SQL query and send it to the database.
  • Change Tracking: It keeps track of changes that occurred in the entities after it has been querying from the database.
  • Persisting Data: It also performs the Insert, Update and Delete operations to the database, based on what the entity states.
  • Caching: DbContext does first level caching by default. It stores the entities which have been retrieved during the life time of a context class.
  • Manage Relationship: DbContext also manages relationship using CSDL, MSL and SSDL in DB-First or Model-First approach or using fluent API in Code-First approach.
  • Object Materialization: DbContext converts raw table data into entity objects.

The following is an example of SchoolDBEntities class (context class that derives DbContext) generated with EDM for SchoolDB database in the previous section.

 

using System;    using System.Data.Entity;    using System.Data.Entity.Infrastructure;    using System.Data.Entity.Core.Objects;    using System.Linq;        public partial class SchoolDBEntities : DbContext    {        public SchoolDBEntities()            : base("name=SchoolDBEntities")        {        }            protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            throw new UnintentionalCodeFirstException();        }            public virtual DbSet
Courses { get; set; } public virtual DbSet
Standards { get; set; } public virtual DbSet
Students { get; set; } public virtual DbSet
StudentAddresses { get; set; } public virtual DbSet
Teachers { get; set; } public virtual DbSet
View_StudentCourse { get; set; } public virtual ObjectResult
GetCoursesByStudentId(Nullable
studentId) { var studentIdParameter = studentId.HasValue ? new ObjectParameter("StudentId", studentId) : new ObjectParameter("StudentId", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction
("GetCoursesByStudentId", studentIdParameter); } public virtual int sp_DeleteStudent(Nullable
studentId) { var studentIdParameter = studentId.HasValue ? new ObjectParameter("StudentId", studentId) : new ObjectParameter("StudentId", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_DeleteStudent", studentIdParameter); } public virtual ObjectResult
> sp_InsertStudentInfo(Nullable
standardId, string studentName) { var standardIdParameter = standardId.HasValue ? new ObjectParameter("StandardId", standardId) : new ObjectParameter("StandardId", typeof(int)); var studentNameParameter = studentName != null ? new ObjectParameter("StudentName", studentName) : new ObjectParameter("StudentName", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction
>("sp_InsertStudentInfo", standardIdParameter, studentNameParameter); } public virtual int sp_UpdateStudent(Nullable
studentId, Nullable
standardId, string studentName) { var studentIdParameter = studentId.HasValue ? new ObjectParameter("StudentId", studentId) : new ObjectParameter("StudentId", typeof(int)); var standardIdParameter = standardId.HasValue ? new ObjectParameter("StandardId", standardId) : new ObjectParameter("StandardId", typeof(int)); var studentNameParameter = studentName != null ? new ObjectParameter("StudentName", studentName) : new ObjectParameter("StudentName", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_UpdateStudent", studentIdParameter, standardIdParameter, studentNameParameter); } }

As you can see in the above example, context class (SchoolDBEntities) includes entity set of type DbSet<TEntity> for all the entities.

Learn more about  class here. It also includes functions for the stored procedures and views included in EDM.

 

Context class overrides OnModelCreating method.

Parameter DbModelBuilder is called Fluent API, which can be used to configure entities in the Code-First approach.

Instantiating DbContext:

You can use DbContext by instantiating context class and use for CRUD operation as shown below.

using (var ctx = new SchoolDBEntities()){            //Can perform CRUD operation using ctx here..}

Getting ObjectContext from DbContext:

DBContext API is easier to use than ObjectContext API for all common tasks. However, you can get the reference of ObjectContext from DBContext in order to use some of the features of ObjectContext. This can be done by using IObjectContextAdpter as shown below:

using (var ctx = new SchoolDBEntities()){    var objectContext = (ctx as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext;            //use objectContext here..}

EDM also generates entity classes. Learn about the different types of entity in the next chapter.

 

转载于:https://www.cnblogs.com/chucklu/p/5113155.html

你可能感兴趣的文章
关于Python装饰器,这11条你不知道,别说你精通Python装饰器
查看>>
阿里云配置Https
查看>>
Pr学习笔记
查看>>
Tex学习笔记
查看>>
二维数组中的查找
查看>>
java面向对象基础总结
查看>>
java第一次实验总结&第三周总结
查看>>
第四周总结&第二次实验报告
查看>>
AlwaysOn 执行备份任务
查看>>
Jenkins构建基于.NET Framework的web程序
查看>>
Jenkins构建基于.NET Core的web程序
查看>>
为什么要用Kubernetes?
查看>>
kubernetes实战(二十六):kubeadm 安装 高可用 k8s 1.16.x dashboard 2.x
查看>>
《博客园美化》添加雪花/修改icon
查看>>
JS对比时间大小
查看>>
《ECharts》ECharts学习日记
查看>>
《H5 App开发》安卓安装最新版本失败
查看>>
js获取开始年与结束年之间的年份
查看>>
《VUE》vue使用echarts
查看>>
《博客园美化》鼠标点击特效
查看>>