ASP.NET Core 2.1 EF-一对一关系仅在关系的一侧生成外键约束

时间:2019-01-24 11:16:56

标签: c# entity-framework asp.net-core ef-migrations

我有以下两种型号:

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>后,我注意到生成的迁移为ShoppingCartId表(由AspNetUsers类表示的表)中的ApplicationUser列创建了一个FK,但是相反,在ShoppingCart表的一侧,没有为UserId列创建FK。

任何建议如何解决此问题?

2 个答案:

答案 0 :(得分:1)

您的关系是错误的。

用户不需要“拥有”购物车(或者至少不必(例如,当新注册时),购物车“属于”用户。您可能还想以一种方式建模,即用户(也许不是现在,但后来)是多个购物车的所有者。

所以:

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

答案 1 :(得分:0)

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

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