代码优先约束违规

时间:2013-04-16 22:09:53

标签: c# entity-framework code-first

我无法在不违反外键约束的情况下删除EF Code First(新数据库)中的对象。

我有三个类,Job,Ticket和Notes。 Job有0,1门票和许多笔记。我想删除db.Job.Remove(作业)的作业(及其相应的票据/备注),但这会导致作业和票证之间的FK违规。我应该如何构建/注释类?

提前致谢。
以下代码段定义了对象/关系:

public WorkflowEntities() : base("CodeFirstWorkflow") { }

    public DbSet<Job> Job { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        // Should create a 1:0,1 between Job and Ticket with ticket being optional
        modelBuilder.Entity<Ticket>()
            .HasRequired(e => e.Job)
            .WithOptional(e => e.Ticket);
    }
}

public class Job {
    public int JobId { get; set; }

    public virtual Ticket Ticket { get; set; }
    public virtual ICollection<Notes> Notes { get; set; }
}

public class Ticket {
    public int TicketId { get; set; }
    public int JobId { get; set; }

    public virtual Job Job { get; set; }
}

public class Notes {
    public int NotesId { get; set; }
    public int JobId { get; set; }

    public virtual Job Job { get; set; }
}

1 个答案:

答案 0 :(得分:0)

Job方面配置:

modelBuilder.Entity<Job>()
.HasMany(p => p.Ticket)
.WithRequired()
.HasForeignKey(c => c.JobId)
.WillCascadeOnDelete(true);