有没有办法选择颜色,然后选择鞋子的尺码?因为我的
代码时,我选择了颜色,然后选择了其更改为的大小
不同的产品。我的数据库设计错了吗。
是的。关于你的数据库设计,很难评论它是正确的还是错误的,因为我们不知道要求是什么。然而,对于这种场景,或者我们可以说对于电子商务购物车的设计,我们通常按产品表、产品变体表进行设计。在产品变体中,我们包括颜色、尺寸、SKU、价格和数量。
因此,我们不能说你的设计是错误的,可能是你按照要求做的。但如果有一个变体表,或者产品的颜色和尺寸列表,我们仍然可以根据产品的尺寸过滤产品。
为了利用您的产品ERD,我将您的产品表写如下:
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public List<string> Colors { get; set; }
public List<string> Sizes { get; set; }
}
笔记
为了执行我这样做的测试,你可以根据你的要求进行修改。
现在,让我们假设您在数据库中有以下产品列表:
List<Product> products = new List<Product>
{
new Product { ProductID = 1, Name = "Nike Shoe", Colors = new List<string>{"Black", "White"}, Sizes = new List<string>{"8", "9", "10"}},
new Product { ProductID = 2, Name = "Adidas T-Shirt", Colors = new List<string>{"Red", "Blue", "Green"}, Sizes = new List<string>{"S", "M", "L"}},
new Product { ProductID = 3, Name = "Puma Jacket", Colors = new List<string>{"Black", "Grey"}, Sizes = new List<string>{"M", "L"}},
new Product { ProductID = 4, Name = "Reebok Shorts", Colors = new List<string>{"Blue", "Grey"}, Sizes = new List<string>{"S", "M", "L"}},
new Product { ProductID = 5, Name = "New Balance Sneakers", Colors = new List<string>{"Red", "Blue"}, Sizes = new List<string>{"9", "10", "11"}},
new Product { ProductID = 6, Name = "Under Armour Hoodie", Colors = new List<string>{"Grey", "Black"}, Sizes = new List<string>{"S", "M", "L"}},
new Product { ProductID = 7, Name = "Fila Pants", Colors = new List<string>{"Black", "Navy"}, Sizes = new List<string>{"M", "L", "XL"}},
new Product { ProductID = 8, Name = "Converse Shoes", Colors = new List<string>{"White", "Black"}, Sizes = new List<string>{"7", "8", "9"}},
new Product { ProductID = 9, Name = "Vans Sneakers", Colors = new List<string>{"Black", "Checkerboard"}, Sizes = new List<string>{"8", "9", "10"}},
new Product { ProductID = 10, Name = "Asics Running Shoes", Colors = new List<string>{"Blue", "Yellow"}, Sizes = new List<string>{"8", "9", "10"}},
};
现在,我想获得每种特定产品的所有尺寸。这样我就可以像下面这样做:
string searchName = "Nike Shoe";
string searchColor = "Black";
var sizes = products
.Where(p => p.Name == searchName && p.Colors.Contains(searchColor))
.SelectMany(p => p.Sizes)
.Distinct()
.ToList();
Console.WriteLine($"Sizes for {searchName} in {searchColor}:");
foreach (var size in sizes)
{
Console.WriteLine(size);
}
备选方式:
您也可以尝试此查询:
var sizes = products
.Where(p => p.ProductName == searchName && p.Color.ColorName == searchColor)
.Select(p => p.Size.SizeName)
.Distinct()
.ToList();
输出
笔记
这是其中一种方式,也可能有其他方式,这取决于表的设计和偏好。