We are going to configure a 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 a reference property of Standard class with StandardId foreignKey property and Standard class has a collection property for Students. So this DataAnnotation will result in a 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() { StudentsList = 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 they 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 a One-to-Many relationship between the 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); }
Another 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); }
The code shown above will create the following database:
The Entity Data Model in the designer will appear like the diagram shown below:
No comments:
Post a Comment