Entity Relationships

Entity Relationships:

Here, you will learn how entity framework manages the relationships between entities.

Entity framework supports three types of relationships, same as database: 1) One to One 2) One to Many, and 3) Many to Many.

We have created an Entity Data Model for the SchoolDB database in the Create Entity Data Modelsection. The following figure shows the visual designer for that EDM with all the entities and relationships among them.

Let‘s see how each relation (association) is being managed by entity framework.

One-to-One Relationship:

As you can see in the above figure, Student and StudentAddress have a One-to-One relationship (zero or one). A student can have only one or zero address. Entity framework adds Student navigation property into StudentAddress entity and StudentAddress navigation entity into Student entity. Also, StudentAddress entity has StudentId property as PrimaryKey which makes it a One-to-One relationship.

The following code snippet shows Student and StudentAddress entity classes.

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; }
}

public partial class StudentAddress
{
    public int StudentID { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    public virtual Student Student { get; set; }
}

As you can see in the above code, Student entity class includes StudentAddress navigation property and StudentAddress includes Student navigation property with foreign key property StudentId. This way EF handles one-to-one relationship between entities.

One-to-Many Relationship:

The Standard and Teacher entities have a One-to-Many relationship marked by multiplicity where 1 is for One and * is for many. This means that Standard can have many Teachers whereas Teacher can associate with only one Standard.

To represent this, The Standard entity has the collection navigation property Teachers (please notice that it‘s plural), which indicates that one Standard can have a collection of Teachers (many teachers). And Teacher entity has a Standard navigation property (Not a Collection) which indicates that Teacher is associated with one Standard. Also, it contains StandardId foreign key (StandardId is a PK in Standard entity). This makes it One-to-Many relationship.

The following code snippet shows Standard and Teacher entity class created by EDM.

public partial class Standard
{
    public Standard()
    {
        this.Students = new HashSet<Student>();
        this.Teachers = new HashSet<Teacher>();
    }

    public int StandardId { get; set; }
    public string StandardName { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Student> Students { get; set; }
    public virtual ICollection<Teacher> Teachers { get; set; }
}

public partial class Teacher
{
    public Teacher()
    {
        this.Courses = new HashSet<Course>();
    }

    public int TeacherId { get; set; }
    public string TeacherName { get; set; }
    public Nullable<int> StandardId { get; set; }
    public Nullable<int> TeacherType { get; set; }

    public virtual ICollection<Course> Courses { get; set; }

    public virtual Standard Standard { get; set; }
}

As you can see in the above code snippet, Standard entity class has Teachers property of type ICollection, so that it can contain multiple Teacher objects. (It initializes Teachers property with HashSet<Teacher> in the constructor, so that you can add Teacher objects into collection without worrying about initializing it.)

Also, Teacher entity class includes Standard property with StandardId for foreign key property. Entity framework includes this foreign key property because we checked Include foreign key columns in the model in the EDM wizard while creating EDM in the Create Entity Data Model section.

Many-to-Many Relationship:

Student and Course have Many-to-Many relationships marked by * multiplicity. It means one Student can enrol for many Courses and also, one Course can be be taught to many Students.

The database design includes StudentCourse joining table which includes the primary key of both the tables (Student and Course table). Entity Framework represents many-to-many relationships by not having entityset for the joining table in CSDL, instead it manages this through mapping.

As you can see in the above figure, Student entity includes Courses property and Course entity includes Students property to represent many-to-many relationship between them.

The following code snippet shows Student and Course entity classes.

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; }
}

public partial class Course
{
    public Course()
    {
        this.Students = new HashSet<Student>();
    }

    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public System.Data.Entity.Spatial.DbGeography Location { get; set; }
    public Nullable<int> TeacherId { get; set; }

    public virtual Teacher Teacher { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

Note: Entity framework supports many-to-many relationship only when the joining table (StudentCourse in this case) does NOT include any columns other than PKs of both the tables. If the join tables contain additional columns, such as DateCreated, then the EDM creates entity for middle table as well and you will have to manage CRUD operation for many-to-many entities manually.

Open EDM in XML view. You can see that SSDL has StudentCourse entityset, but CSDL doesn‘t have StudentCourse entityset. Instead, it‘s being mapped in the navigation property of the Student and Course entity. In MSL (C-S Mapping), it has mapping between Student and Course put into the StudentCourse table in <AssociationSetMapping/>

Thus, Many-to-Many relationship is being managed by C-S mapping in EDM. So when you add a Student in a Course or a Course in a Student entity and when you save it, it will then insert PK of the added student and course in StudentCourse table. So this mapping not only enables a convenient association directly between the two entities, but also manages querying, inserts, and updates across this joint.

Entity Graph:

When an entity has a relationship with other entities, then the full object hierarchy is called an ‘entity graph‘. For example the following is a Student entity graph, that includes hierarchy of Student entity with Standard, StudentAddress & Course entities.

时间: 2024-08-02 20:01:12

Entity Relationships的相关文章

Entity Framework 基础

一.什么是Entity Framework 微软官方提供的ORM工具,ORM让开发人员节省数据库访问的代码时间,将更多的时间放到业务逻辑层代码上.EF提供变更跟踪.唯一性约束.惰性加载.查询事物等.开发人员使用Linq语言,对数据库操作如同操作Object对象一样省事. EF有三种使用场景,1. 从数据库生成Class,2.由实体类生成数据库表结构,3.  通过数据库可视化设计器设计数据库,同时生成实体类. O/RM是什么? ORM 是将数据存储从域对象自动映射到关系型数据库的工具.ORM主要包

Global Financial Applications uses the following Public tables

来自文档: Oracle  Financial Applications Technical Reference Manual  更多明细参考文档     Table Name                                                 Description AP_AE_HEADERS_ALL                            Accounting entry headers table (See page 3 – 8

JI_5

Part I. The CV Review Pass the CV to THREE developers Each dev should mark YES/NO on the CV Reject any CVs with TWO No's Part II. The Phone Interview 1. What *EXACTLY* did you code last? Have them explain in detail.. Then discuss within that context…

JPA 教程

Entities An entity is a lightweight persistence domain object. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity c

Entity Framework Configuring Relationships with the Fluent API

相关链接:Configuring Relationships with the Fluent API Configuring a Required-to-Optional Relationship (One-to-Zero-or-One 1…0,1) 以下示例,表示1…0,1的关系.OfficeAssignment表有一个属性InstructorID,它是一个主键也是一个外键. HasKey方法用于配置主键. // Configure the primary key for the Office

Entity Framework 5.0 Code First全面学习

目录(?)[+] 不贴图片了,太累. Code First 约定 借助 CodeFirst,可通过使用 C# 或Visual Basic .NET 类来描述模型.模型的基本形状可通过约定来检测.约定是规则集,用于在使用 Code First 时基于类定义自动配置概念模型.约定是在 System.Data.Entity.ModelConfiguration.Conventions 命名空间中定义的. 可通过使用数据注释或Fluent API 进一步配置模型.优先级是通过 Fluent API 进行

ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航

ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅.但是,由于本人英语水平有限,难免有翻译不准确或错误的地方,请大家踊跃提出宝贵的意见,以进行修正.本书一共18章,下面列出各章的英文目录: Chapter 1: Building a Basic MVC Web Site Chapter 2: Creating Views, Controllers,

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 package and in .NET framework. The .NET framework 4.0/4.5 included EF core API, whereas EntityFramework.dll via NuGet package included EF 5.0 specifi

Entity Framework Tutorial Basics(3):Entity Framework Architecture

Entity Framework Architecture The following figure shows the overall architecture of the Entity Framework. Let us now look at the components of the architecture individually: EDM (Entity Data Model): EDM consists of three main parts - Conceptual mode