簡體   English   中英

級聯刪除-映射到表的復雜類型

[英]Cascade on delete - Complex type mapped to a table

請考慮以下關系:

汽車(實體)1 ----------------------> *車輪(實體)

車輪(實體)1 ---------> 1螺母(復雜類型)

車輪(實體)1 ---------> 1輪輞(復雜類型)

Nut和Rim復雜類型都映射到名為Nuts和Rims的表。 我正在使用Wheel ID作為螺母和輪輞的主鍵。

現在,當嘗試使用代碼刪除Car時,出現以下異常:

System.InvalidOperationException: The operation failed: The relationship could not be changed   because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
at System.Data.Entity.Core.Objects.ObjectContext.PrepareToSaveChanges(SaveOptions options)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean  executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()

嘗試在MS-SSMS中執行此操作時,出現以下錯誤:DELETE語句與REFERENCE約束“ FK_dbo.Nuts_dbo.Wheel_Id”沖突。 數據庫“ DatabaseName”的表“ dbo.Nuts”的列“ Id”中發生了沖突。

鑒於復雜類型是實體的必需參數並具有一對一關系,因此在這種情況下默認情況下為什么不將層疊刪除默認設置為ON? 其次,應該如何刪除CAR及其相關的多個Wheels以及所有相關的Nuts和Rims。 最后,以我為例,汽車有數千個車輪。 在代碼中還是使用存儲過程是個好主意?

謝謝。

正如本·羅賓遜(Ben Robinson)在評論中提到的那樣,使用[ComplexType]賦予類的目的是將其屬性映射到包含類型的表中的列。 不應有“堅果”或“輪輞”表。 如果這不是期望的行為,則它們不應為復雜類型。

讓我們假設它們不應該是復雜的類型,並弄清楚為什么它們不是級聯刪除的原因。 專注於螺母,並假設您未使用流利的配置,我懷疑您將需要具有“螺母上的滾輪”以及WheelId的導航屬性。 我認為WheelId將標有[Key]和[ForeignKey(Wheel)]。 要點是導航屬性。

使用流利的配置,您將導航屬性設置為Wheel,然后在Wheel的配置中,您將具有:

HasRequired(wheel => wheel.Nut)
  .WithRequiredDependent(nut => nut.Wheel);

要注意的另一點是,如果不是按照您的喜好生成的,則可以通過方法參數在外鍵創建的遷移過程中修改級聯刪除。

最后,回答有關批量刪除的問題:如果您刪除Car並級聯刪除Wheel,則級聯刪除將在數據庫中完成,這應該很快。 如果要分別刪除汽車的多個車輪,請查看Entity Framework Extensions: http : //efe.codeplex.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM