Back to: Entity Framework Tutorials For Begineers and Professionals
Configure One-to-One Relationships in Entity Framework Fluent API
In this article, I am going to discuss how to configure One-to-Zero or One-to-One relationships between two entities using Entity Framework Fluent API with Examples. Let us understand this with an example. We are going to implement One-to-Zero or One-to-One relationship between the following Student and StudentAddress entities.
Student.cs
Create a class file with the name Student.cs and then copy and paste the following code into it.
namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual StudentAddress Address { get; set; } } }
StudentAddress.cs
Create a class file with the name StudentAddress.cs and then copy and paste the following code into it.
namespace EFCodeFirstDemo { public class StudentAddress { public int StudentAddressId { get; set; } public string AddressLine1 { get; set; } public string AddressLine2 { get; set; } public int PinCode { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public virtual Student Student { get; set; } } }
To learn more about Entity Relationship please visit the following URL.
https://dotnettutorials.net/lesson/relationships-between-entities-in-entity-framework/
When a Primary Key (PK) of one table becomes the Primary Key (PK) and Foreign Key (FK) in another table in a relational database such as SQL Server, then it is said to be in a One-to-One or One-to-Zero relationship between the two database tables.
So, we need to configure the above Student and StudentAddress entities in such a way that Entity Framework API should create the Students and StudentAddresses tables in the Database and makes the StudentId column in the Students table as the Primary Key (PK) and StudentAddressId column in the StudentAddresses table as Primary Key (PK) and Foreign Key (FK).
Note: In the One-To-One or One-To-Zero relationship, a row in table A can have one or zero matching rows in table B, and vice versa is also true.
How to Configure One-to-Zero-or-One Relationship using Fluent API?
We can configure the One-to-Zero-or-One relationship between two entities using both Data Annotation Attribute and Fluent API. We have already discussed configuring One to One relationship between the two entities using the ForeignKey Data Annotation Attribute. Now, let us proceed and try to understand how to Configure One-to-Zero or One-to-One relationships between two entities using Entity Framework Fluent API. To implement this, we need to use the following HasOptional() and WithRequired() Fluent API methods.
- HasOptional(): It configures an optional relationship from the entity type. Instances of the entity type will be able to be saved to the database without this relationship being specified. The foreign key in the database will be nullable.
- WithRequired(): It configures the relationship to be optional:required with a navigation property on the other side of the relationship.
Now, modify the context class as follows. The following code sets a one-to-zero or one-to-one relationship between the Student and StudentAddress entities using Entity Framework Fluent API.
using System.Data.Entity; namespace EFCodeFirstDemo { public class EFCodeFirstContext : DbContext { public EFCodeFirstContext() : base("name=MyConnectionString") { //Setting the Database Initializer as DropCreateDatabaseAlways Database.SetInitializer(new DropCreateDatabaseAlways<EFCodeFirstContext>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Configure One to Zero or One to One Relationships between Student and StudentAddress modelBuilder.Entity<Student>() // Mark Address property optional in Student entity .HasOptional(std => std.Address) //Mark Student property as required in StudentAddress entity. //Cannot save StudentAddress without Student .WithRequired(add => add.Student); } public DbSet<Student> Students { get; set; } public DbSet<StudentAddress> StudentAddresses { get; set; } } }
In the above code, we start with the Student entity. The HasOptional() method configures the Address navigation property in the Student entity as optional (not required when saving the Student entity). Then, the WithRequired() method makes the Student navigation property of the StudentAddress entity as required (required means when saving the StudentAddress entity; it will throw an exception when the StudentAddress entity is saved without the Student navigation property). This will also make the StudentAddressId as ForeignKey as well as Primary Key.
Next, modify the Main method of the Program class as follows. Here, while creating the student Entity, we have specified the StudentAddress reference property.
using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var studentAddress = new StudentAddress() { AddressLine1 = "Text1", AddressLine2 = "Text2"}; var student = new Student() {FirstName = "Pranaya", LastName = "Rout", Address = studentAddress}; context.Students.Add(student); context.SaveChanges(); Console.WriteLine("Student Added"); } Console.ReadKey(); } } }
So, we can configure a one-to-zero or one-to-one relationship between two entities where the Student entity can be saved without attaching the StudentAddress object to it but the StudentAddress entity cannot be saved without attaching an object of the Student entity. This makes one end required.
Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.
With the above changes in place, run the application and verify the database and you should see the following.
In the next article, I am going to discuss How to Configure One-to-Many Relationships in Entity Framework Fluent API with Examples. Here, in this article, I try to explain How to Configure the One-to-One or One-to-Zero Relationships between Entities in Entity Framework Fluent API with Examples. I hope you enjoyed this Configure One-to-One or One-to-Zero Relationship using Entity Framework Fluent API article. Please give your valuable feedback and suggestions about this article.