EF Code First Additional column in join table for

2020-01-30 11:15发布

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?

1条回答
家丑人穷心不美
2楼-- · 2020-01-30 12:15

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); 
}
查看更多
登录 后发表回答