I'm using ModelBuilder to map an existing database to POCOs. I have courses, students, and meetings. Here are the tables
CREATE TABLE Courses (
CourseID int,
Name string)
CREATE TABLE Students(
StudentID int,
Name string)
CREATE TABLE Courses_Students (
CourseID int,
StudentID int)
CREATE TABLE Meetings (
MeetingID int,
CourseID int,
MeetDate datetime)
And the POCOs
public class Course {
public int CourseID { get; set; }
public string Name { get; set; }
public virtual ICollection<CourseMeeting> Meetings { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student {
public int StudentID { get; set; }
public string Name { get; set; }
}
public class Meeting {
public int MeetingID { get; set; }
public int CourseID { get; set; }
public DateTime MeetDate { get; set; }
}
The table mapping works great:
modelBuilder.Entity<Course>().MapSingleType().ToTable("Courses");
modelBuilder.Entity<Student>().MapSingleType().ToTable("Students");
modelBuilder.Entity<Meeting>().MapSingleType().ToTable("Meetings");
And the many-to-many mapping with a join table and without a navigation property works (i.e. there is no Students.Courses property specified on WithMany()
)
modelBuilder.Entity<Course>()
.HasMany(c => c.Students)
.WithMany()
.Map(StoreTableName.FromString("Courses_Students"),
(c, s) => new { CourseID = c.CourseID, StudentID = s.StudentID});
But I'm having trouble mapping the other relationship that doesn't have a join table. This obviously isn't right:
modelBuilder.Entity<Course>().HasMany(c => c.Meetings).WithMany();
Because it wants a join table: Invalid object name 'dbo.Course_Meetings'
. I can add a Course
property to the Meeting
object and then use
modelBuilder.Entity<Course>()
.HasMany(c => c.Meetings)
.WithOptional(m => m.Course)
.HasConstraint((c, m) => c.CoursID == me.CourseID);
But I'd like to do this without the navigation property. Is this possible with EF4 and an existing database?