Tuesday, December 10, 2013

Configure One-to-Many Relationship

We are going to configure One-to-Many relationship between Student and Standard as many students are studying in one standard.

Configure One-to-Many relationship using DataAnnotation:

Student entity class has reference property of Standard class with StandardId foreignKey proeprty and Standard class has collection property for Students. So this DataAnnotation will result in One-to-Many relationship.
     
    public class Student
    {
        public Student() { }

        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }

         public int StdandardId { get; set; }
        
        public virtual Standard Standard { get; set; }
    }
        
    
    public class Standard
    {
        public Standard()
        {
            Students = new List<Student>();
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }
        
Configure One-to-Many relationship using Fluent API:

Suppose your Student and Standard entity class doesn’t follow code first conventions and have different property names, for example:
   
    public class Student
    {
        public Student(){ }

        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }

        //StdId is not following code first conventions name
        public int StdId { get; set; }

        public virtual Standard Standard { get; set; }
    }
        
    
    public class Standard
    {
        public Standard()
        {
            StudentsList = new List<Student>();
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Student> StudentsList { get; set; }
    }
        
So you can use Fluent API to configure One-to-Many relationship between Student and Standard entity classes:
    
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            //one-to-many 
            modelBuilder.Entity<Student>().HasRequired<Standard>(s => s.Standard)
            .WithMany(s => s.StudentsList).HasForeignKey(s => s.StdId);

    }
        
Other possible way:
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            //one-to-many
            modelBuilder.Entity<Standard>().HasMany<Student>(s => s.StudentsList)
            .WithRequired(s => s.Standard).HasForeignKey(s => s.StdId);
    }
        
Above code will create following database:
one-to-one relationship in code first

Entity Data Model in designer will look like below:
one-to-one relationship in code first


Download Sample Project:

Download Entity Framework Sample Project

No comments:

Post a Comment