Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First Additional column in join table for ordering purposes

I have two entities that have a relationship for which I create a join table

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Image> Images { get; set; }
}


public class Image
{
    public int Id { get; set; }
    public string Filename { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

        modelBuilder.Entity<Student>()
            .HasMany(i => i.Images)
            .WithMany(s => s.Students)
            .Map(m => m.ToTable("StudentImages"));
}

I would like to add an additional column to allow chronological ordering of the StudentImages.

Where should I add insert the relevant code?

like image 490
Nicholas Murray Avatar asked Sep 02 '11 21:09

Nicholas Murray


1 Answers

Do you want to use that new column in your application? In such case you cannot do that with your model. Many-to-many relation works only if junction table doesn't contain anything else than foreign keys to main tables. Once you add additional column exposed to your application, the junction table becomes entity as any other = you need third class. Your model should look like:

public class StudentImage 
{
    public int StudentId { get; set; }
    public int ImageId { get; set; }
    public int Order { get; set; }
    public virtual Student Student { get; set; }
    public virtual Image Image { get; set; }
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<StudentImage> Images { get; set; }
}


public class Image
{
    public int Id { get; set; }
    public string Filename { get; set; }
    public virtual ICollection<StudentImage> Students { get; set; }
}

And your mapping must change as well:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<StudentImages>().HasKey(si => new { si.StudentId, si.ImageId });

    // The rest should not be needed - it should be done by conventions
    modelBuilder.Entity<Student>()
                .HasMany(s => s.Images)
                .WithRequired(si => si.Student)
                .HasForeignKey(si => si.StudentId); 
    modelBuilder.Entity<Image>()
                .HasMany(s => s.Students)
                .WithRequired(si => si.Image)
                .HasForeignKey(si => si.ImageId); 
}
like image 84
Ladislav Mrnka Avatar answered Oct 03 '22 05:10

Ladislav Mrnka