代码之家  ›  专栏  ›  技术社区  ›  John Dyer

EF4在没有导航的现有数据库上映射一对多

  •  3
  • John Dyer  · 技术社区  · 15 年前

    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");
    

    使用联接表而不使用导航属性的多对多映射也可以工作(即没有Students.Courses 上指定的属性 WithMany() )

    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 回复  |  直到 15 年前
        1
  •  1
  •   Gats    14 年前

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

    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()