EF4 One-to-many mapping in an existing database without navigation

I am 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 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; }
}

Table mapping works fine:

modelBuilder.Entity<Course>().MapSingleType().ToTable("Courses");
modelBuilder.Entity<Student>().MapSingleType().ToTable("Students");
modelBuilder.Entity<Meeting>().MapSingleType().ToTable("Meetings");

And a many-to-many mapping is performed with the connection table and without the navigation property (that is, there is no Students.Courses property specified in 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 displaying other relationships that don't have a join table. This is clearly wrong:

modelBuilder.Entity<Course>().HasMany(c => c.Meetings).WithMany();

Because he needed the connection table: Invalid object name 'dbo.Course_Meetings'. I can add a property Courseto the object Meetingand then use

modelBuilder.Entity<Course>()
    .HasMany(c => c.Meetings)
    .WithOptional(m => m.Course)
    .HasConstraint((c, m) => c.CoursID == me.CourseID);

But I would like to do this without a navigation property. Is this possible with EF4 and the existing database?

+3
1

, (, , ), .

, .

public class Meeting {
        public int MeetingID { get; set; }
        public int CourseID { get; set; }
        public DateTime MeetDate { get; set; }

        public Course { get; set; }
}

:

modelBuilder.Entity<Meeting>(m => new {
        MeetingId = m.Meeting,
        MeetDate = m.MeetDate,
        CourseId = m.Course.Id
})
.HasRequired(m => m.Course)
.WithMany()
+1

Source: https://habr.com/ru/post/1758774/


All Articles