违反代码第一约束
本文关键字:约束 代码 | 更新日期: 2023-09-27 18:09:28
我在不违反外键约束的情况下删除EF代码优先(新DB)中的对象时遇到麻烦。
我有三个类,工作,票和笔记。工作有0,1票和许多笔记。我想用db.Job.Remove(job)删除一个作业(及其相应的票据/笔记),但这会导致作业和票据之间的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; }
}
从Job
侧配置:
modelBuilder.Entity<Job>()
.HasMany(p => p.Ticket)
.WithRequired()
.HasForeignKey(c => c.JobId)
.WillCascadeOnDelete(true);