我正在使用实体框架 6.1.1。我需要在联结表中添加一个额外的字段,该联结表是使用 Fluent API 正确创建的。我知道这对于 Fluent API 是不可能的,并且我必须创建一个模型类,但问题是我无法设法将 fluent api 配置映射到实体模型类,而最终会删除联结表并重新创建它。
我有两个模型类:Docente 和 Lezione。
public class Docente
{
public int Id { get; set; }
public string Nome { get; set; }
[Required]
public string Cognome { get; set; }
public virtual ICollection<Lezione> LezioniDocente { get; set; }
}
public class Lezione
{
public int Id { get; set; }
public string Programma { get; set; }
public virtual ICollection<Docente> LezioniDocente { get; set; }
}
以及正确设置表“LezioneDocente”的配置类:
public class LezioneConfiguration: EntityTypeConfiguration<Lezione>
{
public LezioneConfiguration()
{
ToTable("Lezioni");
Property(c => c.TS).IsRowVersion();
HasMany(d => d.LezioniDocente).WithMany(e => e.LezioniDocente).Map(
w => w.ToTable("LezioneDocente")
.MapLeftKey("LezioneId")
.MapRightKey("DocenteId")
);
}
}
现在我有必要在这个表中添加一个额外的列(RuoloId),所以我需要将 fluent API 配置映射到一个模型类。我尝试通过添加一个新模型类并修改 Docente 和 Lezione 类来引用新模型“LezioniDocente”来做到这一点,如下所示:
public class LezioneDocente
{
[Key, Column(Order = 0)]
public int LezioneId { get; set; }
[Key, Column(Order = 1)]
public int DocenteId { get; set; }
public int RuoloDocenteId { get; set; }
public virtual Docente Docente { get; set; }
public virtual Lezione Lezione { get; set; }
public virtual RuoloDocente RuoloDocente { get; set; }
}
public class Docente
{
public int Id { get; set; }
public string Nome { get; set; }
[Required]
public string Cognome { get; set; }
public virtual ICollection<LezioneDocente> LezioniDocente { get; set; }
}
public class Lezione
{
public int Id { get; set; }
public string Programma { get; set; }
public virtual ICollection<LezioneDocente> LezioniDocente { get; set; }
}
public class LezioneDocenteConfiguration : EntityTypeConfiguration<LezioneDocente>
{
public LezioneDocenteConfiguration()
{
HasRequired(_ => _.Lezione)
.WithMany(_ => _.LezioniDocente)
.HasForeignKey(_ => _.LezioneId);
HasRequired(_ => _.Docente)
.WithMany(_ => _.LezioniDocente)
.HasForeignKey(_ => _.DocenteId);
ToTable("LezioneDocente");
}
}
当我添加新迁移以反映更改时,它不可避免地会在 LezioneDocente 表上调用 DropTable。
public partial class test : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.LezioneDocente", "LezioneId", "dbo.Lezioni");
DropForeignKey("dbo.LezioneDocente", "DocenteId", "dbo.Docenti");
DropIndex("dbo.LezioneDocente", new[] { "LezioneId" });
DropIndex("dbo.LezioneDocente", new[] { "DocenteId" });
CreateTable(
"dbo.LezioneDocente",
c => new
{
LezioneId = c.Int(nullable: false),
DocenteId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.LezioneId, t.DocenteId })
.ForeignKey("dbo.Docenti", t => t.DocenteId, cascadeDelete: true)
.ForeignKey("dbo.Lezioni", t => t.LezioneId, cascadeDelete: true)
.Index(t => t.DocenteId)
.Index(t => t.LezioneId);
DropTable("dbo.LezioneDocente");
}
}
我错过了什么吗?如何在不删除现有表的情况下将流畅的 API 关系映射到模型类?我还尝试在不指定新列的情况下编写 LezioneDocente 类,但它最终还是删除了表。