c# - asp.net MVC 中的关系

c# - Relationships in asp.net MVC

我不太了解建立关系,我做错了什么?我在尝试登录时遇到此错误:

The property 'CartId' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.

购物车 class:

public class EquipmentHireCart
{
    [Key]
    public int CartId { get; set; }

    public int AmountInCart { get; set; }
    public double TotalCost { get; set; }

    //Navigational properties
    public ICollection<Equipment> Items { get; set; }


    [ForeignKey("UserId")]
    public int UserId { get; set; }
    public virtual ApplicationUser CartCustomer { get; set; }


    public EquipmentHireCart()
    {
        Items = new HashSet<Equipment>();
    }

}

应用程序用户Class:

public class ApplicationUser : IdentityUser
{
    [Key]
    public int UserId { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string InputUserName { get; set; }

    public DateTime DateOfBirth { get; set; }
    public string Gender { get; set; }
    public int Age { get; set; }

    public string HouseNumber { get; set; }
    public string Street { get; set; }
    public string Town { get; set; }
    public string PostCode { get; set; }

    public string MemberType { get; set; }


    //Navigational properties

    [ForeignKey("CartId")]
    public int CartId { get; set; }
    public virtual EquipmentHireCart CustomerCart { get; set; }

你评论的错误基本上是@Eric Yeoman 什么引起的

但我想补充一点。您不需要两个 class 中的外键,它是一对一的关系,您可以导航到父级。此外,您必须将外键标记为 null 才能输入记录,否则您将收到密钥违规错误。

这是一个例子(我没有测试它,因为我没有visual studio):

public class ApplicationUser
{
    [Key]
    public int UserId { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    // ...


    [InverseProperty("CartCustomer")]
    public virtual EquipmentHireCart CustomerCart { get; set; }

}


public class EquipmentHireCart
{
    [Key, ForeignKey("CartCustomer")]
    public int CartId { get; set; }

    public int AmountInCart { get; set; }

    // ...

    public virtual ApplicationUser CartCustomer { get; set; }
}