We are going to configure One-to-One relationship between Student and StudentAddress. As you may know that one to one relationship happens when primary key of one table becomes PK & FK in another table. Here, StudentId is a Primary key of Student table so StudentId should be PK and FK in StudentAddress table in order to have one to one (one to zero or one) relationship between them.
Configure one to zero or one relationship using DataAnnotation:
public class Student { public Student() { } public int StudentId { get; set; } [Required] public string StudentName { get; set; } [Required] public virtual StudentAddress StudentAddress { get; set; } }
public class StudentAddress { [Key, ForeignKey("Student")] public int StudentId { get; set; } public string Address1 { get; set; } public string Address2 { get; set; } public string City { get; set; } public int Zipcode { get; set; } public string State { get; set; } public string Country { get; set; } public virtual Student Student { get; set; } }
As you can see in above Student and StudentAddress class, we haven’t done anything special in Student class because StudentId follows the conventions so it will become PK. Now, we use Key and ForeignKey attribute for StudentId in StudentAddress class to mark it as PK as well as FK. So thus it will create one-to-one relationship between Student and StudentAddress.
Configure One-to-One relationship using Fluent API:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<StudentAddress>() .HasKey(e => e.StudentId); modelBuilder.Entity<StudentAddress>() .Property(e => e.StudentId) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); modelBuilder.Entity<StudentAddress>() .HasRequired(e => e.Student) .WithRequiredDependent(s => s.StudentAddress); base.OnModelCreating(modelBuilder); }
Above code will create following database:
You can check the relationship between Student and StudentAddress in the database as below:
If you create entity data model of created database then it will look like this:
You will learn how to create one-to-many relationship in the next chapter.
Download Sample Project:
No comments:
Post a Comment