获取实体的DbContext [英] Get DbContext for Entities
问题描述
我想使用 DbContext
进行实验。我有一个现有的ASP.NET MVC应用程序使用EF 4.2。我可以让我的实体使用:
var context = new MyEntities();
这样做很好。
但是如何得到相同的数据,由一个 DbContext
表示?
所以我猜你使用EDMX设计器提供的默认代码生成器 - 它将使用 ObjectContext
和重量 EntityObject
基础实体
如果要使用DbContext,您必须:
- 关闭默认代码生成 - 在属性窗口中删除EDMX文件的自定义工具
- 下载并安装(您可以直接从Visual Studio中的扩展管理器获取)
- 在EF设计器中,从设计器表面(不在实体)的上下文菜单中选择添加代码生成项
现在,EF将向y添加两个.tt文件我们的项目 - 一个将负责为您的EDMX文件中定义的每个实体或复杂类型创建一个新类,第二个将负责创建从 DbContext
派生的类和暴露为所有实体类型设置
Okay, I feel a bit foolish for having to ask this but I guess my understanding of the inner workings of Entity Framework is lacking.
I'd like to experiment with work with DbContext
. I have an existing ASP.NET MVC application using EF 4.2. I can get my entities using:
var context = new MyEntities();
And this works just fine.
But how the heck to I get the same data represented by a DbContext
?
So I guess you are using default code generator provided by EDMX designer - it will use ObjectContext
and heavy weight EntityObject
based entities.
If you want to use DbContext you must:
- Turn off that default code generation - in property window remove Custom Tool for EDMX file
- Download and install DbContext T4 generator (you can get it directly from extension manager in Visual Studio)
- In EF designer select Add Code Generation Item from context menu in the designer surface (not on entity)
Now EF will add two .tt files to your project - one will be responsible for creating a new class for every entity or complex type defined in your EDMX file and the second will be responsible for creating class derived from DbContext
and exposing sets for all your entity types
这篇关于获取实体的DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!