我有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");
}
流利的配置是好的,問題是不同的。你能分享刪除代碼嗎? –