A relationship in Entity framework is that there is a situation that exists between two database tables in which one table has a foreign key and the foreign key has reference the primary key(PK)
Of the another table, A relationship allow relationship database to split and store data in different tables. for example if we want to store student private information and student education information then we need two tables.
One table for student private information and another table for student education information.
In Entity framework there are 3 type of relationship
- One-to-One Relationships
- One-to-many/Many to One Relationships
- Many-to-Many Relationships
One-to-One Relationships :
Here we will understand one to one Entity relationship b/w student and StudentCollageInfo. As One-to- one relationship happens when primary key of one table become PK and FK of another table.
In our example StudentID is the PK(primary key) of student table and StudentID will be Foreign key (FK) in StudentCollageInfo table for the relationship b/w the tables.
Notice that in SqlServer One To One relationship technically not possible it always One to Zero or Zero.
Firstly we will understand this with Code first approach for this we have to declare property.
One-to-Zero-or-One entity relationship using Fluent API:
The below example for one-to-zero or one relationship between Student and StudentAddress using Fluent API.
In above example, we set primary key(PK) to StudentId for Studentcollageinfo because it doen't follow Code First conventions for primary(PK). Then in second line, HasOptional method make StudentCollageInfo property nullable then WithRequired method will create inverse relationship by making StudentId column as forgion key in StudentcollageInfo table. Thus, StudentId will be PK and FK in StudentAddress which makes one-to-zero or one relationship.
Alternatively, we can also configure Studentcollageinfo entity as shown below.