Create Entity Data Model:

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.

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 clickNext.

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. 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.

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"?>
<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.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
<connectionStrings>
<add name="SchoolDBEntities" connectionString="metadata=res://*/SchoolDB.csdl|res://*/SchoolDB.ssdl|res://*/SchoolDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=SchoolDB;integrated security=True;multipleactiveresultsets=True;application name=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.

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.

public partial class Student
{
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; }
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.

Select 'XML (text) Editor' in the 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.

Entity Framework Tutorial Basics(5):Create Entity Data Model的更多相关文章

  1. Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

    Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...

  2. Entity Framework Tutorial Basics(42):Colored Entity

    Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...

  3. Entity Framework Tutorial Basics(27):Update Entity Graph

    Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...

  4. Entity Framework Tutorial Basics(40):Validate Entity

    Validate Entity You can write custom server side validation for any entity. To accomplish this, over ...

  5. Entity Framework Tutorial Basics(26):Add Entity Graph

    Add Entity Graph using DbContext: Adding entity graph with all new entities is a simple task. We can ...

  6. Entity Framework Tutorial Basics(13):Database First

    Database First development with Entity Framework: We have seen this approach in Create Entity Data M ...

  7. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  8. Entity Framework Tutorial Basics(32):Enum Support

    Enum in Entity Framework: You can now have an Enum in Entity Framework 5.0 onwards. EF 5 should targ ...

  9. Entity Framework Tutorial Basics(31):Migration from EF 4.X

    Migration from Entity Framework 4.1/4.3 to Entity Framework 5.0/6.0 To migrate your existing Entity ...

随机推荐

  1. LKDBHelper Sqlite操作数据库

    首先这里要说明一下,为什么用FMDB而不用Core Data呢,因为我们不知道Core Data是如何映射对象里面的属性关系的,如果我们更改了属性的话,就会报错 首先是创建LKDBHelper对象 L ...

  2. CAP理论、BASE理论

    从分布式一致性谈到CAP理论.BASE理论 https://www.cnblogs.com/szlbm/p/5588543.html 问题的提出 在计算机科学领域,分布式一致性是一个相当重要且被广泛探 ...

  3. Network Saboteur (深搜递归思想的特殊使用)

    个人心得:对于深搜的使用还是不到位,对于递归的含义还是不太清楚!本来想着用深搜构成一个排列,然后从一到n分割成俩个数组,然后后面发现根本实现不了,思路太混乱.后来借鉴了网上的思想,发现用数组来标志,当 ...

  4. C++中rand()函数的用法

    1.rand()不需要参数,它会返回一个从0到最大随机数的任意整数,最大随机数的大小通常是固定的一个大整数. 2.如果你要产生0~99这100个整数中的一个随机整数,可以表达为:int num = r ...

  5. Oracle记录(一)Oracle简介与安装

    Oracle笔记(一) Oracle简介及安装 一.轨迹 二.Oracle简介 Oracle是现在全世界最大的数据库提供商,编程语言提供商,应用软件提供商,它的地位等价于微软的地位. Oracle在古 ...

  6. 用Json Template在Azure上创建Cisco CSR路由器

    Azure的ARM模式可以通过Json的模板创建VM.本文以Cisco的CSR的image为例,介绍如何用Json的创建VM. 一.Cisco CSR的Image 首先把Cisco CSR的image ...

  7. Extjs5.0 学习之路【资源篇】

    磨刀不误砍柴工. 先收集资源,然后再开始学习之路. Extjs5.0 文件下载 API-5.0 API离线包 http://cdn.sencha.com/downloads/docs/ext-docs ...

  8. POJ3249(DAG上的dfs)

    Test for Job Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 10567   Accepted: 2482 Des ...

  9. hihoCoder#1067(离线算法求LCA)

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 上上回说到,小Hi和小Ho用非常拙劣——或者说粗糙的手段山寨出了一个神奇的网站,这个网站可以计算出某两个人的所有共同祖先中 ...

  10. Java学习之系统高可用性渲染接口日志自动服务降级

    背景:公司都追求系统的高可用性,这里不可用时间就是其中很重要的一个指标,为此在做系统功能升级迭代的过程中如何快速处理异常恢复正常功能极为重要.现在对新增模块的要求是都增加开关,方便快速关闭异常模块,但 ...