实体框架 - 生成类 [英] Entity Framework - Generating Classes
问题描述
我有一个现有的数据库。我希望有一个方法来生成从该数据库中的类文件。但是,我似乎看到了从类文件生成数据库的很多东西。
I have an existing database. I was hoping there was a way to generate class files from this database. However, I seem to see a lot of generating the database from the class files.
有没有办法从使用实体框架现有的数据库生成的类文件?如果是的话怎么样?有人能指出我的教程?
Is there a way to generate class files from an existing database using the Entity Framework? If so how? Can someone point me to a tutorial?
推荐答案
1)首先你需要使用数据库来生成 EDMX
模式。要做到这一点,你应该新项目添加到您的项目:
1) First you need to generate EDMX
model using your database. To do that you should add new item to your project:
- 选择
ADO.NET实体数据模型
从模板列表。 - 在选择模型内容页面上,选择从数据库中选择生成,然后单击下一步。
- 选择您的数据库。
- 在选择数据库对象页,检查表。如果你需要选择视图或存储过程。
- Select
ADO.NET Entity Data Model
from the Templates list. - On the Choose Model Contents page, select the Generate from Database option and click Next.
- Choose your database.
- On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.
所以,现在你有 Model1.edmx
文件在你的项目。
So now you have Model1.edmx
file in your project.
2)使用你的模型生成类:
2) To generate classes using your model:
- 打开你的
EDMX
模型设计。 - 在设计面点右键 - >添加code代项目...
- 选择在线模板。
- 选择
EF 4.x版的DbContext发生器C#
。 - 单击添加。
- Open your
EDMX
model designer. - On the design surface Right Click –> Add Code Generation Item…
- Select Online templates.
- Select
EF 4.x DbContext Generator for C#
. - Click ‘Add’.
注意两个项目被添加到您的项目:
Notice that two items are added to your project:
-
Model1.tt
(这个模板在你的模型生成非常简单的POCO类为每个实体) -
Model1.Context.tt
(这个模板生成一个派生的DbContext用于查询和持久化数据)
Model1.tt
(This template generates very simple POCO classes for each entity in your model)Model1.Context.tt
(This template generates a derived DbContext to use for querying and persisting data)
3)读/写数据例如:
3) Read/Write Data example:
var dbContext = new YourModelClass(); //class derived from DbContext
var contacts = from c in dbContext.Contacts select c; //read data
contacts.FirstOrDefault().FirstName = "Alex"; //edit data
dbContext.SaveChanges(); //save data to DB
不要忘了,你需要的EntityFramework 4.x版。您可以下载EF 4.1的位置:实体框架4.1
这篇关于实体框架 - 生成类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!