我有2个实体由一对多的关系连接如下(I第一次使用码):使用EF禁用级联删除?
public class Computer
{
[Key]
public int ComputerId { get; set; }
[Required]
public int ComputerIdInventory { get; set; }
[DataType(DataType.Date)]
public DateTime? AcquisitionDate { get; set; }
[DataType(DataType.Date)]
public DateTime? LastUpdate { get; set; }
public string Comment { get; set; }
//Foreign keys
public int? ComputerModelId { get; set; }
public int? EmployeeId { get; set; }
//Navigation properties
public virtual ICollection<Screen> Screens { get; set; }
}
public class Screen
{
[Key]
public int ScreenId { get; set; }
[Required]
public int ScreenIdInventory { get; set; }
public string Comment { get; set; }
//Foreign keys
public int? ComputerId { get; set; }
//Navigation properties
public virtual Computer Computer { get; set; }
}
当我删除链接到一个或多个屏幕的计算机,我已经以下错误:
[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.
我已经看了很多帖子,我试过两件事情,似乎已经工作了他人。我改变了“OnModelCreating”的方法,并补充说:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
我想这太:
modelBuilder.Entity<Computer>()
.HasMany<Screen>(c => c.Screens)
.WithOptional(s => s.Computer)
.WillCascadeOnDelete(false);
但没有解决方案的奋力...难道我做错了什么?我也更新了数据库,但没有任何改变。我是否必须完全删除数据库并重新创建它才能将这些更改考虑在内?
非常感谢!
编辑: 这里是删除代码
public ActionResult DeleteConfirmed(int id)
{
Computer computer = db.Computers.Find(id);
db.Computers.Remove(computer);
db.SaveChanges();
return RedirectToAction("Index");
}
流利的配置是好的,问题是不同的。你能分享删除代码吗? –