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 table 中的 ShoppingCartId 列创建了一个 FK(由ApplicationUser class),但在 ShoppingCart table 的另一侧,没有为 UserId 列创建 FK。

有什么解决方法的建议吗?

如果您将 public ApplicationUser ApplicationUser { get; set; } ApplicationUser 作为 属性 放入您的实体模型,它会为您创建关系。

但我不建议您这样做,不要将所有应用程序表与应用程序标识紧密耦合。还建议将您的身份验证上下文放在单独的数据库上下文架构中

你搞错了关系。

用户没有 "have" 购物车(或者至少不需要,例如在新注册时),购物车 "belongs to" 用户。您可能还希望以用户(可能不是现在,但以后)是多个购物车的所有者的方式对此进行建模。

所以:

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; }
}