Note that there are some explanatory texts on larger screens.

plurals
  1. POEF4 Mapping one-to-many on existing database without navigation
    text
    copied!<p>I'm using ModelBuilder to map an existing database to POCOs. I have courses, students, and meetings. Here are the tables</p> <pre><code>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) </code></pre> <p>And the POCOs</p> <pre><code>public class Course { public int CourseID { get; set; } public string Name { get; set; } public virtual ICollection&lt;CourseMeeting&gt; Meetings { get; set; } public virtual ICollection&lt;Student&gt; 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; } } </code></pre> <p>The table mapping works great:</p> <pre><code>modelBuilder.Entity&lt;Course&gt;().MapSingleType().ToTable("Courses"); modelBuilder.Entity&lt;Student&gt;().MapSingleType().ToTable("Students"); modelBuilder.Entity&lt;Meeting&gt;().MapSingleType().ToTable("Meetings"); </code></pre> <p>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 <code>WithMany()</code>)</p> <pre><code>modelBuilder.Entity&lt;Course&gt;() .HasMany(c =&gt; c.Students) .WithMany() .Map(StoreTableName.FromString("Courses_Students"), (c, s) =&gt; new { CourseID = c.CourseID, StudentID = s.StudentID}); </code></pre> <p>But I'm having trouble mapping the other relationship that doesn't have a join table. This obviously isn't right:</p> <pre><code>modelBuilder.Entity&lt;Course&gt;().HasMany(c =&gt; c.Meetings).WithMany(); </code></pre> <p>Because it wants a join table: <code>Invalid object name 'dbo.Course_Meetings'</code>. I can add a <code>Course</code> property to the <code>Meeting</code> object and then use </p> <pre><code>modelBuilder.Entity&lt;Course&gt;() .HasMany(c =&gt; c.Meetings) .WithOptional(m =&gt; m.Course) .HasConstraint((c, m) =&gt; c.CoursID == me.CourseID); </code></pre> <p>But I'd like to do this without the navigation property. Is this possible with EF4 and an existing database?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload