[英]Entity framework migrations ignoring WillCascadeOnDelete
例如,看看這個問題。 實體框架 (EF) 代碼優先級聯刪除,用於一對零或一關系
我有一個正常的上下文等。
如果我更改任何內容,我可以根據Add-Migration test
生成一個新的遷移。
但是,如果我將 WillCascadeOnDelete() 從 true 更改為 false 或添加一些 true,則實體框架會忽略它。
我首先將代碼與數據庫中生成的模型一起使用。 在生成的模型中,一切都在WillCascadeOnDelete(false)
。 所以現在我將它從 false 更改為 true 但它被實體框架忽略了。
我也試過這個: http : //msdn.microsoft.com/en-us/data/jj591620.aspx#CascadeDelete 。
添加此行后......如果我添加Add-Migration newTest
則沒有任何變化。
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()
這也被Add-Migration thirdTest
。
modelBuilder.Conventions.Add<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Add<ManyToManyCascadeDeleteConvention>()
我可以用 WillCascadeOnDelete 改變一切……它被忽略了!
如果我更改其他所有內容,它會起作用並將附加到新的遷移中...
此構造的主要類如下。
[Table("SomeToThing")]
public class SomeToThing : Base
{
[Column("Some")]
public Guid SomeId { get; set; }
[ForeignKey("SomeId")]
public virtual Some Some { get; set; }
[Column("Thing")]
public Guid ThingId { get; set; }
[ForeignKey("ThingId")]
public virtual Thing Thing { get; set; }
}
我有這個表:
SomeToThing
有額外的變量,因為我無法將Some
直接映射到Thing
。
我知道這個線程很舊,但我只是遇到了同樣的問題。
我的解決方案是刪除遷移源文件並從頭開始重新搭建它。
在我第一次嘗試時,我忘記設置.WillCascadeOnDelete(false)
,並且出於充分的理由,SQL Server 由於周期而拒絕了遷移。 然后,當我在OnModelCreating
方法中刪除級聯后嘗試使用相同的名稱重新構建遷移時,EF 只是不會選擇那些特定的更改。
然后我刪除了遷移源文件並運行Add-Migration SameMigrationName
。 由於 MSSQL 接受了遷移腳本,級聯刪除已被刪除,並且似乎有效。 順便說一句,我正在使用 EF 6.1.3。
關於我遇到的問題,我想提到的一件事是我添加了以下代碼(到我的“OnModelCreating”,即 DbContext):
modelBuilder.Entity<MyEntityTwo>()
.HasMany(e => e.MyEntityOne)
.WithRequired(e => e.MyEntityTwo)
.HasForeignKey(e => e.MyEntityTwoId)
.WillCascadeOnDelete(false);
但是我在定義 MyEntityOne 的表已經定義之后添加了這個,即在以前的遷移中。
事實證明,因為我在表已經定義之后將它添加到 OnModelCreating 中,所以當我添加一個新的遷移時,實體框架並沒有“不”選擇 willcascadeondelete(false)。
為了解決這個問題,我必須手動將以下內容添加到(新的)遷移中:
DropIndex(...this was created by EF for me already. Not important...);
DropForeignKey("MyEntityOne", "<name of Foreign key goes here ie FK_MyEntityOne_...etc>");
AddForeignKey("MyEntityOne", "MyEntityTwoId", "MyEntityTwo", "Id", cascadeDelete:false);
AlterColumn(...this was created by EF for me already. Not important...);
CreateIndex(...this was created by EF for me already. Not important...);
通過添加AddForeignKey 行,使用cascadeDelete: false,它將重新應用帶有cacade on delete false 的外鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.