我尝试使用EF6代码优先禁用级联删除。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
当我尝试删除表中的记录时,我收到错误
&#34;无法删除主键值,因为引用了此键 关键仍然存在。 [外键约束名称= FK_dbo.OperatorActivity_dbo.Operator_OperatorId]&#34;
我的模特
public class OperatorActivity
{
public Guid Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool Synched { get; set; }
public virtual Station Station { get; set; }
public Guid StationId { get; set; }
public virtual Operator Operator { get; set; }
public Guid OperatorId { get; set; }
}
public class Operator
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string Login { get; set; }
public byte[] Password { get; set; }
public virtual Network Network { get; set; }
public virtual ICollection<Station> Stations { get; set; }
public virtual ICollection<OperatorActivity> Activities { get; set; }
public virtual ICollection<Refill> Refills { get; set; }
public override string ToString()
{
return this.Name + " " + this.LastName;
}
}
如何禁用级联删除?
答案 0 :(得分:1)
虽然在保留子行的同时删除引用的(父)行是不合逻辑的,但是为了允许这样做,您应该删除外键约束。
在 MySQL 数据库中运行:
alter table OperatorActivity drop
foreign key FK_dbo.OperatorActivity_dbo.Operator_OperatorId
在 SQL Server :
中alter table OperatorActivity drop
constraint FK_dbo.OperatorActivity_dbo.Operator_OperatorId