开发者

EF Code First Additional column in join table for ordering purposes

开发者 https://www.devze.com 2023-04-02 17:59 出处:网络
I 开发者_StackOverflow中文版have two entities that have a relationship for which I create a join table

I 开发者_StackOverflow中文版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?


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); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消