爲什麼我不能刪除父項,而其子項在外鍵上設置爲WillCascadeOnDelete(false)
?實體框架無法刪除父項,當子項具有WillCascadeOnDelete的外鍵(false)
這是父:
public class EA_Client
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[Display(Name = "Client Id")]
public int ClientId { get; set; }
[Display(Name = "User Id")]
public int? UserId { get; set; }
[Display(Name = "Client Name")]
public string ClientName { get; set; }
public virtual AlvinCMSExtension.Models.UserProfile User { get; set; }
public EA_Client()
{
UserId = 0;
ClientName = "";
}
}
這是孩子:
public class EA_Order
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[Display(Name = "Order Id")]
public int OrderId { get; set; }
[Display(Name = "Client Id")]
public int? ClientId { get; set; }
[Display(Name = "Supplier Id")]
public int? SupplierId { get; set; }
[Display(Name = "Total Amount To Pay")]
public decimal TotalAmountToPay { get; set; }
[Display(Name = "Order Time")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime OrderTime { get; set; }
[Display(Name = "Description")]
public string Description { get; set; }
public virtual ICollection<EA_OrderStatus> OrderStatuses { get; set; }
public virtual ICollection<EA_OrderDetail> OrderDetails { get; set; }
public virtual EA_Client Client { get; set; }
public virtual EA_Supplier Supplier { get; set; }
public EA_Order()
{
ClientId = null;
SupplierId = null;
TotalAmountToPay = 0;
OrderTime = DateTime.Now;
Description = "";
}
}
這是孩子的模型構造器:
mb.Entity<EA_Order>().HasOptional<EA_Client>(m => m.Client).WithMany().HasForeignKey(m => m.ClientId).WillCascadeOnDelete(false);
mb.Entity<EA_Order>().HasOptional<EA_Supplier>(m => m.Supplier).WithMany().HasForeignKey(m => m.SupplierId).WillCascadeOnDelete(false);
mb.Entity<EA_Order>().HasMany<EA_OrderStatus>(m => m.OrderStatuses);
mb.Entity<EA_Order>().HasMany<EA_OrderDetail>(m => m.OrderDetails);
每次我試圖刪除父(EA_Client),發生此錯誤:
{「DELETE語句與參考約束\」FK_EAccounting.EA_Order_EAccounting.EA_Client_ClientId \「發生衝突。衝突發生於數據庫\ 「EAccountingDB \」,表\ 「EAccounting.EA_Order \」,列 '客戶端Id'。\ r \ n該語句已終止。「}
如何解決這一問題?我想能夠刪除父母(EA_Client),因爲父母是可選的,意味着可以讓孩子(EA_Order)成爲孤兒院入口。
你在你的子表中有這個Id,你應該將它設置爲null,然後刪除命令 –
這將非常麻煩,因爲我需要將null設置爲具有可選外鍵給EA_Client的其他實體。有沒有辦法讓它自動化? –