http://www.entityframeworktutorial.net/EntityFramework5/create-dbcontext-in-entity-framework5.aspx

官网的教程https://msdn.microsoft.com/en-us/data/jj206878

Here, we are going to create an Entity Data Model (EDM) for SchoolDB database and understand the basic building blocks.

Entity Data Model is a model that describes entities and the relationships between them. Let's create first simple EDM for SchoolDB database using Visual Studio 2012 and Entity Framework 6.

1. Open Visual Studio 2012 and create a console project.

Go to PROJECT menu of visual studio -> {project name} properties - and make sure that the project's target framework is .NET Framework 4.5, as shown below.

2. Now, add Entity Data Model by right clicking on the project in the solution explorer -> Add -> click New Item

and select ADO.NET Entity Data Model from popup, Give the new item the name 'School' and click Add button.

VS2015中默认是找不到这个的,http://stackoverflow.com/questions/23046081/missing-ado-net-entity-data-model-on-visual-studio-2013

http://www.cnblogs.com/chucklu/p/5109747.html自己写了一篇,参照这个,在iso镜像文件中手动安装

3. Entity Data Model Wizard in VS2012 opens with four options to select from:

EF Designer from database for database first approach,

Empty EF Designer model for model first approach,

Empty Code First model and Code First from database for Code-First approach.

We will focus on the database-first approach in the basic tutorials so select EF Designer from database option and click Next.

4. You can choose from your existing DB Connections or create a new connection by clicking on the 'New Connection' button.

We will use the existing DB connection to the SchoolDB Database.【这一步的前提是已经将数据库文件附加到sqlserver2012了】

This will also add a connection string to your app.config file with the default suffix with DB name.

You can change this if you want.  【根据需要选择是否在配置文件中保存敏感信息】

Click 'Next' after you set up your DB connection.

5. In this step, you need to choose the version of Entity Framework. We will use Entity Framework 6.0 in the basic tutorials so select Entity Framework 6.0 and click Next.

Note: If you have already installed the latest version of Entity Framework using NuGet manager as shown in the Setup Environment section then this step of the wizard will no longer appear since you have already installed Entity Framework.

6. This step will display all the Tables, Views and Stored Procedures (SP) in the database.

Select the Tables, Views and SPs you want, keep the default checkboxes selected and click Finish.

You can change Model Namespace if you want.

把Tables,Views,Stored Procedures and Functions全部勾选上

Note:

Pluralize or singularize generated object names checkbox singularizes an entityset name, if the table name in the database is plural.

For example, if SchoolDB has Students table name then entityset would be singular Student.

Similarly, relationships between the models will be pluralized if the table has one-to-many or many-to-many relationship with other tables.

For example, Student has many-to-many relationship with Course table so Student entity set will have plural property name 'Courses' for the collection of courses.

The second checkbox, Include foreign key columns in the model, includes foreign key property explicitly to represent the foreign key.

For example, Student table has one-to-many relationship with Standard table. So every student is associated with only one standard.

To represent this in the model, Student entityset includes StandardId property with Standard navigation导航 property.

If this checkbox is unchecked then it will only include the Standard property, but not the StandardId in the Student entityset.

The third checkbox, Import selected stored procedures and functions into entity model, automatically creates Function Imports for the stored procedures and functions.

You don't need to manually import this, as was necessary prior to Entity Framework 5.0.

7. After clicking on 'Finish', a School.edmx file will be added into your project.

Open EDM designer by double clicking on School.edmx. This displays all the entities for selected tables and the relationships between them as shown below:

EDM also adds a connection string in the config file as shown below.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="SchoolDBEntities" connectionString="metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=LUJUNTAO\MSSQLSERVER2012;initial catalog=SchoolDB;persist security info=True;user id=sa;password=123456;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>

In this way, you can create a simple EDM from your existing database.

Now, let's examine all the building blocks of generated EDM (School.edmx) as shown in the above figure.

Entity-Table Mapping:

Each entity in EDM is mapped with the database table.

You can check the entity-table mapping by right clicking on any entity in the EDM designer -> select Table Mapping.

Also, if you change any property name of the entity from designer then the table mapping would reflect that change automatically.

在EDM设计器中,右键选中某一个实体表,选择Table Mapping

就可以看到列映射,比如StudentID数据库中是int  映射到类中StudentID,类型是Int32

StudentName是varchar类型  映射出来是string类型

Context & Entity Classes:

Every Entity Data Model generates one context class and entity class for each DB table included in the EDM.

Expand School.edmx and see two important files, {EDM Name}.Context.tt and {EDM Name}.tt:

School.Context.tt: This T4 template file generates a context class whenever you change Entity Data Model (.edmx file).

You can see the context class file by expanding School.Context.tt.

The context class resides in {EDM Name}.context.cs file.

The default context class name is {DB Name} + Entities.

For example, the context class name for SchoolDB is SchoolDBEntities, then the context class is derived from DBContext class in Entity Framework. (Prior to EF 5.0 it had been derived from ObjectContext.)

School.tt: School.tt is a T4 template file that generates entity classes for each DB table.

Entity classes are POCO (Plain Old CLR Object) classes.

The following code snippet shows the Student entity.

 using System;
using System.Collections.Generic; public partial class Student
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Student()
{
this.Courses = new HashSet<Course>();
} public int StudentID { get; set; }
public string StudentName { get; set; }
public Nullable<int> StandardId { get; set; }
public byte[] RowVersion { get; set; } public virtual Standard Standard { get; set; }
public virtual StudentAddress StudentAddress { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Course> Courses { get; set; }
}

EDM Designer: EDM designer represents your conceptual model.

It consists of Entities, and associations & multiplicity between the entities.

Initially, it will look exactly like your database table structure but you can add, merge or remove columns, which are not required by your application from this designer.

You can even add a new object in this model, which can have columns from different database tables from context menu, as shown in the figure above.

Remember, whatever changes done here should be mapped with the storage model.

So you have to be careful, while making any changes in the designer.

You can open this EDM designer in XML view where you can see all the three parts of the EDM - Conceptual schema (CSDL), Storage schema (SSDL) and mapping schema (MSL), together in XML view.

Right click on School.edmx -> click 'Open with..', this will open a popup window.

Visual Studio cannot display the model in Design view and in XML format at the same time, so you will see a message asking whether it’s OK to close the Design view of the model.

Click Yes. This will open the XML format view. You can see the following XML view by toggling all outlining as shown below.

You can see SSDL content, CSDL content and C-S mapping content here.

If you expand SSDL and CSDL, each one has some common XML node under each schema node.

You don't need to edit the xml data because this can be accomplished easier in the Model Browser.

Learn about Model Browser in the next section.

Create Entity Data Model的更多相关文章

  1. Entity Framework Tutorial Basics(5):Create Entity Data Model

    Create Entity Data Model: Here, we are going to create an Entity Data Model (EDM) for SchoolDB datab ...

  2. 创建实体数据模型【Create Entity Data Model】(EF基础系列5)

    现在我要来为上面一节末尾给出的数据库(SchoolDB)创建实体数据模型: SchoolDB数据库的脚本我已经写好了,如下: USE master GO IF EXISTS(SELECT * FROM ...

  3. EntityFramework 学习 一 创建实体数据模型 Create Entity Data Model

    1.用vs2012创建控制台程序 2.设置项目的.net 版本 3.创建Ado.net实体数据模型 3.打开实体数据模型向导Entity Framework有四种模型选择 来自数据库的EF设计器(Da ...

  4. Entity Framework的核心 – EDM(Entity Data Model) 一

    http://blog.csdn.net/wangyongxia921/article/details/42061695 一.EnityFramework EnityFramework的全程是ADO. ...

  5. EF,ADO.NET Entity Data Model简要的笔记

    1. 新建一个项目,添加一个ADO.NET Entity Data Model的文件,此文件会生成所有的数据对象模型,如果是用vs2012生的话,在.Designer.cs里会出现“// Defaul ...

  6. 关于VS2010“ADO.NET Entity Data Model模板丢失或者添加失败问题

    我最近在安装vs2010后,添加ADO.NET Entity 实体时发现,我的新建项里面并没有这个实体模型,后来我就在博问里面发表了问题,请求大家帮忙解决,悲剧的是少有人回应啊,呵呵,不过我还是在网上 ...

  7. VS2010中没有ado.net entity data model实体数据模型这一选项-解决办法

    前提先安装VS2010 SP1包. 解决办法: 1.从VS2010的安装盘目录下面的WCU\EFTools找到ADONETEntityFrameworkTools_chs.msi和ADONETEnti ...

  8. [转]Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)

    本文转自:http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-a ...

  9. How to: Use the Entity Framework Model First in XAF 如何:在 XAF 中使用EF ModelFirst

    This topic demonstrates how to use the Model First entity model and a DbContext entity container in ...

随机推荐

  1. 剑指offer--7题

    *题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变. *句子中单词以空格符隔开.为简单起见,标点符号和普通字母一样处理. *例如输入“I am a student.”,则输出“st ...

  2. JDBC编程步骤

    JDBC编程步骤 加载数据库驱动. 通常使用Class类的forName()静态方法来加载驱动. Class.forName(driverClass) dirverClass: mysql---Cla ...

  3. VSFTPD全攻略(/etc/vsftpd/vsftpd.conf文件详解)

    /etc/vsftpd/vsftpd.conf文件详解,分好类,方便大家查找与学习 #################匿名权限控制############### anonymous_enable=YE ...

  4. ASP.NET 大文件上传的简单处理

    在 ASP.NET 开发的过程中,文件上传往往使用自带的 FileUpload 控件,可是用过的人都知道,这个控件的局限性十分大,最大的问题就在于上传大文件时让开发者尤为的头疼,而且,上传时无法方便的 ...

  5. SOA之(3)——面向服务计算基础

    面向服务计算基础(Service-Oriented Computing Fundamentals) 面向服务的计算(Service-Oriented Computing) 面向服务的计算是一个伞状术语 ...

  6. Ext Js学习之IIS理解

    站点分为静态网站和动态网站,纯粹利用html编写的网站属于静态网站,不宜维护和更新而利用C#+extjs等前台+后台技术编写的网站就属于动态站点,有更多的交互,易维护和更新,比如降价的页面,利用htm ...

  7. 单片机模拟 1/2 Bias、1/4 Duty的 LCD 驱动使用方法

    工作原理 方式一     根据 LCD 的驱动原理可知,LCD 像素点上只能加上 AC 电压,LCD 显示器的对比度由 COM脚上的电压值减去 SEG 脚上的电压值决定,当这个电压差大于 LCD 的饱 ...

  8. 小圣求职记B:总集篇

    1. 搜狐sohu 搜狐在正式招聘前邀请了部分应聘者到武汉研发中心开座谈会(因此简历尽量早投,机会多些),有研发的也有产品的,40人左右,座谈会期间介绍了搜狐汽车.北京研发中心.武汉研发中心和搜狐媒体 ...

  9. iOS打电话,发短信,发邮件,打开网址

    //调用自带mail [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://admin@hzl ...

  10. HDU 3790 最短路径问题(SPFA || Dijkstra )

    题目链接 题意 : 中文题不详述. 思路 :无论是SPFA还是Dijkstra都在更新最短路的那个地方直接将花费更新了就行,还有别忘了判重边,话说因为忘了判重边WA了一次. #include < ...