EF4在没有导航的情况下在现有数据库上进行一对多映射

时间:2010-08-09 17:04:19

标签: entity-framework entity-framework-4

我正在使用ModelBuilder将现有数据库映射到POCO。我有课程,学生和会议。这是表格

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)

和POCO

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>().MapSingleType().ToTable("Courses");
modelBuilder.Entity<Student>().MapSingleType().ToTable("Students");
modelBuilder.Entity<Meeting>().MapSingleType().ToTable("Meetings");

使用连接表并且没有导航属性的多对多映射有效(即WithMany()上没有指定Students.Courses属性)

modelBuilder.Entity<Course>()
    .HasMany(c => c.Students)
    .WithMany()
    .Map(StoreTableName.FromString("Courses_Students"), 
        (c, s) => new { CourseID = c.CourseID, StudentID = s.StudentID});

但是我在映射没有连接表的其他关系时遇到了问题。这显然是不对的:

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

因为它想要一个连接表:Invalid object name 'dbo.Course_Meetings'。我可以向Course对象添加Meeting属性,然后使用

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

但我想在没有导航属性的情况下这样做。 EF4和现有数据库是否可以实现这一目标?

1 个答案:

答案 0 :(得分: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()
相关问题