0

I have the following models in my solution:

internal class Customer
{
    [Key]
    public int CustomerId { get; set; }

    [MaxLength(50)]
    public string FirstName { get; set; }

    [MaxLength(50)]
    public string LastName { get; set; }

    [MaxLength(12)]
    public string PhoneNumber { get; set; }
}

internal class Product
{
    [Key]
    public int ProductId { get; set; }

    [MaxLength(100)]
    public string ProductName { get; set; }

    public decimal Price { get; set; }

    public double ProductWeight { get; set; }

    public bool InStock { get; set; }

}

internal class Order
{
    [Key]
    public int OrderId { get; set; }

    [ForeignKey("Customer")]
    public int CustomerId { get; set; }
    public Customer Customer { get; set; }

    public DateTime OrderDate { get; set; }

    [MaxLength(30)]
    public string PoNumber { get; set; }
}

class Cart
{
    public virtual ICollection<Order> Orders { get; set; }

    public virtual ICollection<Product> Products { get; set; }

    public uint Quantity { get; set; }
}

...and DB context

class Store : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<Cart> Carts { get; set; }

}

When I debug, an exception is thrown saying "'Carts' is based on type 'Cart' that has no keys defined". I've removed the Cart class from the DB context and the solution runs fine. I've tried several different ways to declare the keys in the Cart class including:

[ForeignKey("Order")]
[Column(Order = 1)]
public int OrderId { get; set; }
public Order Order { get; set; }


[ForeignKey("Product")]
[Column(Order = 2)]
public int ProductId { get; set; }
public Product Product { get; set; }

or

[Key]
public int OrderId { get; set; }

[Key]
public int ProductId { get; set; }

Any ideas where I might be going wrong? (Please keep in mind this is an educational project so feedback on the DB design is unnecessary)

N-Saba
  • 137
  • 1
  • 1
  • 6
  • 1
    Have you seen the following answer to a similar question? http://stackoverflow.com/a/19792915/858757 – Silvermind Nov 12 '14 at 19:01
  • 1
    Thank you, that worked. It's unfortunate that I tried several similar solutions, just not that exact one. – N-Saba Nov 12 '14 at 19:14
  • possible duplicate of [Mapping composite keys using EF code first](http://stackoverflow.com/questions/19792295/mapping-composite-keys-using-ef-code-first) – Corey Adler Nov 12 '14 at 19:28
  • You still need to use the [Key] attribute, but you have to also specify the Order as well. – Dismissile Nov 12 '14 at 20:44

0 Answers0