实体框架代码优先数据库未与模型同步

时间:2018-09-21 15:34:34

标签: c# entity-framework entity-framework-6

我们是一个小团队,使用实体框架作为我们的对象关系映射(ORM)框架。我们使用git作为源代码控制,在最新的sprint中,我们在两个单独的分支中进行了数据库更改。没有什么不寻常的。

但是,通常我们可以通过添加空白的“合并”迁移来获得正确的模型快照。

https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/teams#option-1-add-a-blank-merge-migration

但是,在我们最新的合并中,确实发生了一些奇怪的事情。我们的模型和数据库不同步。下面的给定模型具有五个属性的组合主键。

public class NotifiedEvent
{
    [Key, Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [MaxLength(15)]
    public string BusinessSystemId { get; set; }

    [Key, Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CaseId { get; set; }

    [Key, Column(Order = 2)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [MaxLength(5)]
    public string Action { get; set; }

    [Key, Column(Order = 3)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Cycle { get; set; }

    [ForeignKey("BusinessSystemId,CaseId,Action,Cycle")]
    public virtual TPRenewalCycle TPRenewalCycle { get; set; }

    [Key, Column(Order = 4)]
    [ForeignKey("TPEvent")]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int EventNo { get; set; }

    public virtual TPEvent TPEvent { get; set; }

    [ForeignKey("BusinessSystemId,CaseId,Action,Cycle,EventNo")]
    public virtual TPCaseEvent TpCaseEvent { get; set; }

    public int NotifiedBatchId { get; set; }

    public virtual NotifiedBatch NotifiedBatch { get; set; }

    [Key, Column(Order = 5)]
    public DateTime EventDate { get; set; }

    public DateTime Created { get; set; }

    public DateTime Updated { get; set; }
}

但是,数据库中有一个六列的复合主键。我知道它已被编辑,但现在找不到它的迁移。

enter image description here

当我尝试创建新迁移时,它看起来像这样:

public partial class RemoveDueDatefromNotifiedEvent : DbMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

如果我再次将DueDate键添加到模型中,则实体框架会尝试将现有键再次添加到数据库中。

[Key, Column(Order = 6)]
public DateTime DueDate { get; set; }

迁移:

public partial class RemovedDueDatefromNotifiedEvent : DbMigration
{
    public override void Up()
    {
        DropPrimaryKey("dbo.NotifiedEvents");
        AddColumn("dbo.NotifiedEvents", "DueDate", c => c.DateTime(nullable: false, precision: 0, storeType: "datetime2"));
        AddPrimaryKey("dbo.NotifiedEvents", new[] { "BusinessSystemId", "CaseId", "Action", "Cycle", "EventNo", "EventDate", "DueDate" });
    }

    public override void Down()
    {
        DropPrimaryKey("dbo.NotifiedEvents");
        DropColumn("dbo.NotifiedEvents", "DueDate");
        AddPrimaryKey("dbo.NotifiedEvents", new[] { "BusinessSystemId", "CaseId", "Action", "Cycle", "EventNo", "EventDate" });
    }
}

0 个答案:

没有答案