如何在C#

时间:2019-12-09 06:36:47

标签: c# mongodb

我想为电子商务系统提供产品目录服务。 我有“衣服”产品,这些产品的“尺寸”和“颜色”有所不同,例如:

    "Title": "Nike Hoodie Tiger",
    "Price": 69.9,
    "Vars": [
        {
            "Sku": "NH01",
            "Attrs": [{"Size": "XL"}, {"Color": "white"}],
            "Quantity" : 3
        },
                {
            "Sku": "NH02",
            "Attrs": [{"Size": "L"}, {"Color": "white"}],
            "Quantity" : 0
        },
        {
            "Sku": "NH03",
            "Attrs": [{"Size": "M"}, {"Color": "white"}],
            "Quantity" : 1
        }
    ]

然后我有“电视”产品,这些产品的分辨率有所不同:

    "Title": "Sony Bravia 40",
    "Price": 339.9,
    "Vars": [
        {
            "Sku": "TV01",
            "Attrs": [{"Resolution": "FullHD"}],
            "Quantity" : 3
        },
                {
            "Sku": "TV01",
            "Attrs": [{"Resolution": "4K"}],
            "Quantity" : 0
        }
    ]

衣服产品的模型在C#中如下所示:

    public class Product
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string Title { get; set; }
        public decimal Price { get; set; }
        public List<ProductVariations> Vars { get; set; }
    }

    [BsonIgnoreExtraElements]
    public class ProductVariations
    {
        public string Sku { get; set; }
        public List<ProductAttributes> Attrs { get; set; }
        public int Quantity { get; set; }
    }

    public class ProductAttributes
    {
        public string Size { get; set; }
        public string Color { get; set; }
    }

那么我应该使用什么策略来支持其他产品属性,例如电视上的属性? 如果将来我想添加其他属性完全不同的产品怎么办?是否需要重写代码以支持这些属性?

1 个答案:

答案 0 :(得分:1)

很好的问题。由于您不知道类型是将来的实现,因此只能使用明细/值实现。

您的列表可能包含如下数据结构,而不是属性:

public class ProductDetail {
    public DetailType Type;
    public string Value;
}

现在您的attrs可以更改为类似的

`[{ Type: 1, Value: "4k"}]`

并且DetailType可以作为枚举来节省存储空间。

如果detailType枚举有问题,则可以执行以下操作:

public class ProductDetail {
    public string Type;
    public string Value;
}

`[{ Type: "Resolution", Value: "4k"}]`