我有两个实体,我有一个关系,我创建了一个连接表
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"));
}
我想添加一个额外的列,以便按时间顺序排列StudentImages。
我应该在哪里添加插入相关代码?
答案 0 :(得分:24)
您想在应用程序中使用该新列吗?在这种情况下,你不能用你的模型做到这一点。只有当联结表不包含除主表的外键以外的任何内容时,多对多关系才有效。一旦添加了暴露给您的应用程序的其他列,联结表就变成了实体,就像其他任何=您需要第三类一样。您的模型应如下所示:
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; }
}
你的映射也必须改变:
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);
}