The code below, is fine. It works. Things are inserted, stuff appear on the right side on the left side etc. However, there's an issue. Using a program such as LinQPad (https://www.linqpad.net), I am able to query the data and see it listed.
But, trying to do the same in C#, says that the "auto" generated linking table does not exists in the context.
Relationship: Many-to-Many.
I am using Entity Framework 6.
EDIT: What's the purpose of autogenerated linking table if you cannot use it from your C# Windows Application? Using Linq?
My Code First 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");
});
base.OnModelCreating(modelBuilder);
}
Querying from within the LinqPad, works perfectly fine:
void Main()
{
var data = (from s in Students
join sc in StudentCourse on s.StudentID equals sc.FK_StudentID
join c in Courses on c.CourseId equals sc.FK_CourseID
select new { s,c });
Console.WriteLine(data);
}