The code after the tables here, does generate a new dynamic table in the Database. But, I don't know how to access it or how to add linking to it via C# code.
3NF, three tables.
Tables:
public class Student
{
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
public class Course
{
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CourseId { get; set; }
[Index("CourseName", 2, IsUnique = true)]
public string CourseName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
DBContext.cs
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany<Course>(s => s.Courses)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.MapLeftKey("FK_StudentID");
cs.MapRightKey("FK_CourseID");
cs.ToTable("StudentCourse");
});
}
The code above here, creates a table like this:
StudentCourse
=================================
| FK_StudentID | FK_CourseID |
=================================
EDIT: I am looking at this question now, How to define Many-to-Many relationship through Fluent API Entity Framework?
EDIT, Clarification: Sorry for my delay: This is more related to when, e.g. you already have students or add students separately. But, then want to dynamically, connect them to a course or a number of courses. Similarly, you add new courses. But, these can then be taken by students.