簡體   English   中英

實體框架多級刪除

[英]Entity Framework Multiple Cascading Delete

我定義了以下三個模型:User,Room和PlayerRoom:

public class User
{
    public int id { get; set; }
    public string UserName { get; set; }

    //flags user to be deleted when room is no longer available
    public bool temporaryUser { get; set; }

    [JsonIgnore]
    public bool permanent { get; set; }
}

public class Room
{
    public int id { get; set; }
    public string RoomName { get; set; }

    [JsonIgnore]
    public int CreatedById { get; set; }
    public virtual User CreatedBy { get; set; }
}


public class PlayerRoom
{
    public int id { get; set; }

    [JsonIgnore]
    public int RoomId { get; set; }
    public virtual Room Room { get; set; }

    [JsonIgnore]
    public int UserId { get; set; }
    public virtual User User { get; set; }
}

我要完成的工作是設置模型,以便在刪除User或刪除Room時,所有關聯的PlayerRoom將被刪除。

當前,當我生成遷移並運行update-database ,出現錯誤:

Introducing FOREIGN KEY constraint 'FK_dbo.Rooms_dbo.Users_CreatedById' on table 'Rooms' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

無法創建約束。 請參閱先前的錯誤。

根據我所做的研究,是因為可以從層疊中以多種方式刪除PlayerRoom ,但這是預期的行為。

如何獲得遷移工具以生成不會引發此錯誤的遷移?

謝謝!

我最終改變了我的課程,以使他們更具限制性,在這種情況下,實際上效果更好。 我刪除了PlayerRoom對象,並將Room引用移到了用戶對象上。

public class User
{
    public int id { get; set; }
    public string UserName { get; set; }

    //flags user to be deleted when room is no longer available
    public bool temporaryUser { get; set; }

    public bool? isHost { get; set; }

    [JsonIgnore]
    public int? RoomId { get; set; }
    public virtual Room Room { get; set; }

    [JsonIgnore]
    public bool permanent { get; set; }
}

public class Room
{
    public int id { get; set; }
    public string RoomName { get; set; }
}

通過將Room移到用戶而不是在單獨的對象上,它限制了用戶只能在一個Room並且擺脫了我的級聯刪除問題

擺脫了我的級聯刪除問題

EF使用“代碼優先”功能默認將級聯設置為啟用。 要從模型中將其關閉,可以策略性地將“ WillCascadeOnDelete”從相關實體上移開:

.WillCascadeOnDelete(false);

或全球

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();   

暫無
暫無

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

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