EF Relations Object Composition

Slides:



Advertisements
Similar presentations
Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.
Advertisements

Entity Framework Performance SoftUni Team Technical Trainers Software University
Entity Framework: Code First SoftUni Team Technical Trainers Software University
Using SQL Connecting, Retrieving Data, Executing SQL Commands, … Svetlin Nakov Technical Trainer Software University
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Joins, Subqueries, CTE and Indices
Auto Mapping Objects SoftUni Team Database Applications
Working with Fluent API Inheritance Strategies
Static Members and Namespaces
Introduction to Entity framework
Databases basics Course Introduction SoftUni Team Databases basics
Interface Segregation / Dependency Inversion
Services & Dependency Injection
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
C# Database Fundamentals with Microsoft SQL Server
Introduction to Entity Framework
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
C# Databases Advanced with Microsoft SQL Server
Database Design and Rules
EF Advanced Querying Optimize Performance SoftUni Team Advanced
Entity Framework: Code First
Parsing XML XDocument and LINQ
Entity Framework DB From Code, OOP Introduction
Data Definition and Data Types
Databases advanced Course Introduction SoftUni Team Databases advanced
Basic CRUD in SQL Server
Abstraction, Interface, Inheritance, Polymorphism, Override / Overload
Entity Framework: Relations
Caching Data in ASP.NET MVC
Fast String Manipulation
The Right Way Control Flow
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
Transactions in Entity Framework
Exporting and Importing Data
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Combining Data Structures
Best Practices and Architecture
Best practices and architecture
Introduction to Databases
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Exporting and Importing Data
ASP.NET Filters SoftUni Team ASP.NET MVC Introduction
Making big SPA applications
Manual Mapping and AutoMapper Library
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Exporting and Importing Data
CSS Transitions and Animations
Train the Trainers Course
Iterators and Comparators
Hibernate (JPA) Code First Entity Relations
Spring Data Advanced Querying
Entity Framework Advanced Querying SoftUni Team Technical Trainers
Text Processing and Regex API
/^Hel{2}o\s*World\n$/
JavaScript: ExpressJS Overview
CSS Transitions and Animations
Presentation transcript:

EF Relations Object Composition Customizing Entity Models EF Relations SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Contents Object Composition Navigation Properties Table Relationships Attributes © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

sli.do #Entity Questions © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Car Engine Piston Object Composition

Object Composition Object composition denotes a "has-a" relationship E.g. the car has an engine Defined in C# by one object having a property that is a reference to another Person MyDog Age Name Dog

Navigation Properties Navigation properties create a relationship between entities Is either an EntityReference (one to one or zero) or an ICollection (one to many or many to many) They provide fast querying of related records Will automatically create mapping tables Must be declared virtual to enable lazy loading (object proxy) Can be modified by directly setting the reference

Expressed as Properties and Attributes Table Relationships Expressed as Properties and Attributes

One-to-Zero-or-One Expressed in SQL Server as a shared primary key Relationship direction must be explicitly specified with a ForeignKey attribute ForeignKey is placed above the key property and contains the name of the navigation property or vice versa Student Address

One-to-Zero-or-One Implementation public class Student { public int Id { get; set; } public string Name { get; set; } public virtual Address Address { get; set; } } public class Address { [Key] [ForeignKey("Student")] public int Id { get; set; } public string Text { get; set; } public virtual Student Student { get; set; } } Attributes

One-to-Many Most common type of relationship Implemented with a collection inside the parent entity The collection must be initialized in the constructor! Department Employee

One-to-Many Implementation public class Department { public Department() this.Employees = new HashSet<Employee>(); } public int Id { get; set; } … public virtual ICollection<Employee> Employees { get; set; } public class Employee { public int Id { get; set; } … public virtual Department Department { get; set; } }

Many-to-Many Requires a mapping table (auto-generated) Implemented with collections in each entity, referring the other The collections must be initialized in the constructor! Student Course Student Course Student

Many-to-Many Implementation public class Course { public Course() { this.Students = new HashSet<Student>(); } … public virtual ICollection<Student> Students { get; set; } } public class Student { public Student() { this.Courses = new HashSet<Courses>(); } … public virtual ICollection<Course> Courses { get; set; } }

Multiple Relations When two entities are related by more than one key Entity Framework needs help from Inverse Properties Place of Birth Town Person Town Current Residence

Multiple Relations Implementation Person Domain Model – defined as usual public class Person { public int Id { get; set; } public string Name { get; set; } public Town PlaceOfBirth { get; set; } public Town CurrentResidence { get; set; } }

Multiple Relations Implementation (2) Town Domain Model public class Town { public Town() this.Natives = new HashSet<Person>(); this.Residents = new HashSet<Person>(); } public int Id { get; set; } public string Name { get; set; } [InverseProperty("PlaceOfBirth")] public ICollection<Person> Natives { get; set; } [InverseProperty("CurrentResidence")] public ICollection<Person> Residents { get; set; } Point towards related model

Custom Entity Framework Behavior Attributes Custom Entity Framework Behavior

Attributes EF Code First provides a set of DataAnnotaion attributes You can override default Entity Framework behavior To access nullability and size of fields: To access schema customizations: For a full set of configuration options you need the Fluent API using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;

Key order must be explicitly specified Key Attributes Key – explicitly specify primary key When your PK column doesn't contain "Id" in it's name When you want a composite key [Key] public int StudentKey { get; set; } [Key] [Column(Order=1)] public int StudentId { get; set; } [Column(Order=2)] public int CourseId { get; set; } Key order must be explicitly specified

Key Attributes (2) ForeignKey – explicitly link navigation property and foreign key property within the same class (to rename the column) Works in either direction (FK to navigation property or navigation property to FK) public class Client { … public int OrderRefId { get; set; } [ForeignKey("OrderRefId")] public virtual Order Order { get; set; } }

Renaming Objects Table – manually specify the name of the table in the DB [Table("StudentMaster")] public class Student { … } [Table("StudentMaster", Schema="Admin")] public class Student { … }

Renaming Objects (2) Column – manually specify the name of the column in the DB You can also specify order and explicit data type public class Student { … [Column("StudentName", Order=2, TypeName="varchar(50)")] public string Name { get; set; } } Optional parameters

Entity Validation Required – mark a nullable property as NOT NULL in the DB Will throw exception if not set to a value Non-nullable types (e.g. int) will not throw an exception (will be set to language-specific default value) MinLength – specify min length of a string (client validation) MaxLength / StringLength – specify max length of a string (both client and DB validation) Range – set lower and/or upper limits of numeric property (client validation)

Optional unique specifier Other Attributes Index – create index for column Primary key will always have an index NotMapped – property will not be mapped to a column For business logic properties Optional name Optional unique specifier [Index( "INDEX_REGNUM", IsUnique=true )] public int RegistrationNumber { get; set; }

Summary Objects can be composed from other objects to represent complex relationships Navigation properties speed up the traversal of related entities Attributes can be used to express special table relationships and to customize entity behaviour © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Entity Framework Relations https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Databases" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.