我的解决方案中有以下模型:
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; }
}
...和DB上下文
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; }
}
当我调试时,会抛出一个异常,说“'Carts'基于没有定义键的'Cart'类型”。 我从DB上下文中删除了Cart类,解决方案运行正常。 我尝试了几种不同的方法来声明Cart类中的键,包括:
[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; }
或
[Key]
public int OrderId { get; set; }
[Key]
public int ProductId { get; set; }
我可能会出错的任何想法? (请记住这是一个教育项目,因此不需要对数据库设计的反馈)