Search code examples
c#asp.netforeign-keysrelationships

c# - Relationships in asp.net MVC


I'm not really understanding making relationships, what am I doing wrong? I get this error when I try to sign in:

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.

Cart 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>();
    }

}

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

Solution

  • The error you commented on is basically caused by what @Eric Yeoman.

    But I would like to add a point. You don't need foreign keys in both class, it's a one to one relationship and you can navigate to parent. Also, You would have to mark the foreign key as null to be able to enter the record, or you will receive a key violation error.

    Here is an exemple (I don't test it because i'm without 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; }
    }