簡體   English   中英

ASP.NET Core 2.1 EF - 一對一關系僅在關系的一側生成外鍵約束

[英]ASP.NET Core 2.1 EF - One to One relationship generates foreign key constraint only on one side of the relationship

我有以下兩個模型:

public class ApplicationUser : IdentityUser
{
    public int? ShoppingCartId { get; set; }
    public ShoppingCart ShoppingCart { get; set; }
}
public class ShoppingCart
{
    public int Id { get; set; }

    public string UserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

運行Add-Migration <some-name>我注意到生成的遷移為AspNetUsers表(由ApplicationUser類表示的那個)中的ShoppingCartId列創建了一個 FK,但在ShoppingCart表的另一邊,沒有為UserId列創建 FK。

任何建議如何解決這個問題?

你搞錯了關系。

用戶沒有“擁有”購物車(或者至少不必,例如在新注冊時),購物車“屬於”用戶。 您還可能希望以這樣一種方式對此進行建模,即用戶(可能不是現在,而是以后)是多個購物車的所有者。

所以:

public class ApplicationUser : IdentityUser
{
    // Later: public List<ShoppingCart> ShoppingCarts { get; set; }
    public ShoppingCart ShoppingCart { get; set; }
}
public class ShoppingCart
{
    public int Id { get; set; }

    public string UserId { get; set; }
    public ApplicationUser User { get; set; }
}

如果你把public ApplicationUser ApplicationUser { get; set; } public ApplicationUser ApplicationUser { get; set; } public ApplicationUser ApplicationUser { get; set; } ApplicationUser作為一個屬性來你的實體模型,它為您創建的關系。

但我不建議您這樣做,不要將所有應用程序表與應用程序標識緊密耦合。 還建議將您的身份驗證上下文放在單獨的數據庫上下文架構上

暫無
暫無

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

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