簡體   English   中英

與Entity Framework ASP.net MVC中的多個表的可選關系

[英]Optional relationship to more than one table in Entity Framework ASP.net MVC

我正在嘗試構建一個ASP.net MVC應用程序。 我在與數據注釋建立某種聯系時遇到麻煩。

我有3個表,“ Overhours ,“ Accountings ,“ Vacations 每個“ Overhour記錄可以有1個“ Accounting或“ Vacation記錄,但這是可選的。 因此,它不必必須擁有一個。 這是我的Overhour模式:

public class Overhour
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OverhourId { get; set; }

    ....

    public int? AccountingId { get; set; }
    public virtual Accounting Accounting { get; set; }

    public int? VacationId { get; set; }
    public virtual Vacation Vacation { get; set; }
}

我想刪除“ Overhour記錄(如果有的話)時同時刪除“ Vacation和“ Accounting記錄。 當我這樣使用它時,級聯刪除將被禁用。

我嘗試了這個:

public class Overhour
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OverhourId { get; set; }

    ....

    public virtual Accounting Accounting { get; set; }

    public virtual Vacation Vacation { get; set; }
}

級聯刪除有效,但是Entity Framework創建諸如“ Accounting_AccountingId”之類的字段,這也是必需的。 那些不是必需的。

我最后嘗試的是:

public class Overhour
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OverhourId { get; set; }

    ....

    public int AccountingId { get; set; }
    public virtual Accounting Accounting { get; set; }

    public int VacationId { get; set; }
    public virtual Vacation Vacation { get; set; }
}

但這一次它給了我這樣的錯誤:

在表xxx上引入FOREIGN KEY xxx約束可能會導致循環或多個級聯路徑。 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束

我很困惑,我在做什么錯?

謝謝

DELETE CASCADE不能那樣工作。 如果您刪除Overhour ,則也不會刪除任何其他內容。 它的作用方向相反。 如果Accounting是必需的依賴項,並且您刪除了附加到OverhourAccounting實例,則Overhour應該刪除Overhour 如果外鍵可為空,則不會發生這種情況,因為它將被設置為DELETE SET NULL。 但是,無論哪種方式,刪除“ Overhour都不會對“ Accounting或“ Vacation實例產生任何影響。

更新

在這種情況下,創建一對一的關系似乎很容易,因為這種關系的一側是可選的。 所有你需要的是:

public class Overhour
{
    ...

    public int? AccountingId { get; set; } // optional
    public virtual Accounting Accounting { get; set; }
}

public class Accounting
{
    ...

    public int OverhourId { get; set; } // required
    public virtual Overhour Overhour { get; set; }
}

這樣,刪除Overhour也會級聯並刪除關聯的Accounting ,因為它取決於Overhour

只有當關系的雙方都需要時,事情才會變得復雜。 然后,您必須使用fluent config將一個設置為主體,將一個設置為從屬,因為EF當時無法自行做出此決定。

暫無
暫無

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

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