Entity framework EF4在现有数据库上映射一对多,无需导航

Entity framework EF4在现有数据库上映射一对多,无需导航,entity-framework,entity-framework-4,Entity Framework,Entity Framework 4,我正在使用ModelBuilder将现有数据库映射到POCOs。我有课程、学生和会议。这是桌子 CREATE TABLE Courses ( CourseID int, Name string) CREATE TABLE Students( StudentID int, Name string) CREATE TABLE Courses_Students ( CourseID int, StudentID int) CREATE TABLE

我正在使用ModelBuilder将现有数据库映射到POCOs。我有课程、学生和会议。这是桌子

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)
还有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; }
}
但是我在映射另一个没有联接表的关系时遇到了问题。这显然是不对的:

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

但是我想在没有导航属性的情况下执行此操作。对于EF4和现有数据库,这可能吗?

假设它需要联接表(并因此查找它),因为您没有在原始声明中映射属性

尝试手动映射实际表上的属性,如下

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()
modelBuilder.Entity(m=>new{
MeetingId=m.会议,
MeetDate=m.MeetDate,
CourseId=m.Course.Id
})
.HasRequired(m=>m.Course)
.有很多

EF5已经改变了这一点,但我想确保仍将其标记为正确。谢谢。我仍然在EF5中使用类似的方法,但可以肯定的是,生活变得容易多了。不再需要关系映射的“全有或全无”方法,这是一种解脱。
modelBuilder.Entity<Course>()
    .HasMany(c => c.Meetings)
    .WithOptional(m => m.Course)
    .HasConstraint((c, m) => c.CoursID == me.CourseID);
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()