EF5 - > EF6奇怪的迁移行为

时间:2014-09-04 15:37:42

标签: c# entity-framework asp.net-mvc-4

我们有一个ASP.Net MVC4项目,现在已经使用Entity Framework 5一年了。我们刚刚使用NuGet包管理器更新到Entity Framework 6,现在我们在迁移生成中遇到了奇怪的行为。

一个正确存在的多对多表,现在EF想要添加一个额外的列和FK ......并且不会忽略具有[NotMapped]属性的列。我不得不使用.Ignore()

以下是与EF5一起使用的多对多的相关代码,但突然之间不想使用EF6 ......

public class Grade
{
    [Key]
    public int GradeKey { get; set; }
    [Required]
    public string GradeLevel { get; set; }

    public virtual ICollection<Test> Tests { get; set; }
}

public class Test
{
    [Key]
    [HiddenInput(DisplayValue = false)]
    public int TestKey { get; set; }

    ...

    [UIHint("_GradeCheckboxes")]
    [Order(5)]
    [Display(Order = 5)]
    [DisplayName("Grades")]
    public virtual ICollection<Grade> Grades { get; set; }
}

//Fluent API for the join
modelBuilder.Entity<Grade>().HasKey(p => p.GradeKey).HasMany(p => p.Tests).WithMany(d => d.Grades).Map(x => 
{
    x.MapLeftKey("Grade_GradeKey"); 
    x.MapRightKey("Test_TestKey");
    x.ToTable("GradeTests");
});

// Migration
public override void Up()
{
    AddColumn("dbo.Grades", "Test_TestKey", c => c.Int()); // This is a problem
    AlterColumn("dbo.Students", "StateCode", c => c.String()); // This already exists in DB
    AlterColumn("dbo.Students", "SchoolName", c => c.String()); // This already exists in DB
    CreateIndex("dbo.Grades", "Test_TestKey"); // Problem
    CreateIndex("dbo.StudentTests", "StudentKey");
    CreateIndex("dbo.StudentTests", "TestKey"); 
    AddForeignKey("dbo.Grades", "Test_TestKey", "dbo.Tests", "TestKey"); // Problem
    AddForeignKey("dbo.StudentTests", "StudentKey", "dbo.Students", "StudentKey", cascadeDelete: true); // Already exists
    AddForeignKey("dbo.StudentTests", "TestKey", "dbo.Tests", "TestKey", cascadeDelete: true); // Already exists
}

在升级或使用EF6时,是否有其他人遇到此问题。我已经尝试了许多不同的策略和互联网搜索,试图解决这个问题几天了。我甚至删除了__MigrationHistory表并删除了所有迁移,并且仅从模型中重新开始,但它仍然希望在Test_TestKey表中创建Grades列而不是在多对多表中...

1 个答案:

答案 0 :(得分:0)

我已从Grade中删除[Key]属性并进行测试,并在初始化基本数据库时按预期工作

public class Grade
{

    public int GradeKey { get; set; }
    [Required]
    public string GradeLevel { get; set; }

    public virtual ICollection<Test> Tests { get; set; }
}

流畅的api与构建多对多的表格时的行为相同

 modelBuilder.Entity<Grade>()
                    .HasKey(g => g.GradeKey)
                    .HasMany(g => g.Tests)
                    .WithMany(t => t.Grades)
                    .Map(map =>
                        {
                            map.ToTable("GradeTests");
                            map.MapLeftKey("GradeKey");
                            map.MapRightKey("TestKey");
                        });

数据库表

enter image description here