C# 实体框架代码优先,购物车
我是实体框架的新手,我试图使用代码优先的方法实现一个简单的购物车,但我不明白为什么实体会以下面奇怪的方式生成表。以下是我的课程的精简版: Product.csC# 实体框架代码优先,购物车,c#,entity-framework,C#,Entity Framework,我是实体框架的新手,我试图使用代码优先的方法实现一个简单的购物车,但我不明白为什么实体会以下面奇怪的方式生成表。以下是我的课程的精简版: Product.cs public class Product { [Key] public int ID { get; set; } public int ProductCategoryID { get; set; } public string ProductNumber { get; set; } public string Name { get
public class Product
{
[Key]
public int ID { get; set; }
public int ProductCategoryID { get; set; }
public string ProductNumber { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public string Color { get; set; }
public string Capacity { get; set; }
public string CapacityUnitMeasureCode { get; set; }
public decimal Price { get; set; }
public decimal Cost { get; set; }
public int Stock { get; set; }
}
ShoppingCart.cs
public class ShoppingCart
{
[Key]
[Column (Order=1)]
public int ID { get; set; }
[Key]
[Column(Order = 2)]
public int ProductID { get; set; }
public int Quantity { get; set; }
public DateTime CreatedDate { get; set; }
public virtual List<Product> products { get; set; }
}
公共类购物车
{
[关键]
[第列(顺序=1)]
公共int ID{get;set;}
[关键]
[第列(顺序=2)]
public int ProductID{get;set;}
公共整数数量{get;set;}
公共日期时间CreatedDate{get;set;}
公共虚拟列表产品{get;set;}
}
因为这条线
公共虚拟列表产品{get;set;}
实体使用2个附加外键生成产品表:
ShoppingCart\u ID和ShoppingCart\u ProductID
我不明白。我的意图是创建一个与特定购物车关联的产品列表。我做错了什么。有人能帮我照一下吗 由于您在购物车类中将ProductID作为属性之一,并且在购物车中具有虚拟产品集合,EF在购物车和产品类之间建立了关系 正如评论中所建议的,您可以删除产品id类,也可以创建视图模型类,并在购物车和产品类之间建立关系 示例视图模型可以是
public class ShoppingCartProduct
{
[Key]
[Column (Order=1)]
public int ID { get; set; }
[Key]
[Column(Order = 2)]
public int ProductID { get; set; }
}
您可以在此处阅读有关视图模型的内容
您的最佳解决方案是制作一个包含您所有产品及其编号的类
购物车
:
[Table("Cart")]
public class ShopingCart
{
[Key]
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public virtual ICollection<ItemCart> Products { get; set; } // relationship one-to-many
}
如果您想了解更多信息,请查看本页:
试着让思考变得简单:你只有3种可能的关系:
希望对你有用 首先,此行“public int ProductID{get;set;}”不应在ShoppingCart类定义中。移除它,看看会发生什么。第二,我希望有一个额外的表来保持shoppingcart及其相关产品之间的关系。这似乎解决了我的问题。将“公共虚拟列表产品{get;set;}”替换为“公共虚拟产品产品{get;set;}”,这似乎纠正了ProductID上的FK约束。而不在产品表上添加其他键。-谢谢,伙计。我认为虽然这解决了你的问题,但它不会是你想要的设计。因为一个购物车可能包含多个产品。一种产品可以在不同的购物卡上,这是一种多对多的关系。您需要一个额外的表来反映relationship@Eric. 实际上,它应该可以工作,正如您所看到的ShoppingCart类有一个复合PK(ID,ProductID),而ID是CardID,对于customer表还有一个FK。所以“是”并不是完全规范化的,但因为购物车项目来来去去去(订单提交时)。所以我不认为这是个问题谢谢你的意见
[Table("ItemCart")]
public class ItemCart
{
[Key]
public int Id { get; set; }
public int Quantity { get; set; }
public virtual Product Product { get; set; } // relationship one-to-one
}