允许用户创建具有自定义属性的新数据类型

Allowing user to create new data types with custom properties

我正在开发一个网络项目,用户应该能够创建自定义类型的商品,其中包含任意数量的不同类型的属性(数字、文本等)。例如:一个有名称、价格和物理尺寸的盒子,以及一个有名称、价格和体积的瓶子。

在代码和数据库中表示这一点的最佳方式是什么? 我的第一个想法是为一件商品创建一个基本模板,并将所有自定义数据转储为字符串化 JSON 的单个字段中。缺点是此数据不能用于 IQueryable 搜索、过滤和排序。

我还可以考虑创建一个单独的 table,我将在其中存储所有商品的所有自定义字段,并通过关系引用它们。然而,这不会导致缩放问题,因为我基本上将所有自定义属性存储在单个 table.

中的所有位置。

这是最好的方法吗?当然,在 .NET Core 中无法动态创建新 类 和数据库 table,但是还有哪些其他选项?

感谢您的宝贵时间,

我在当前的副项目中这样做,而且我过去也这样做过。基本上,您将有一个基数 Product table(或任何您想命名的名称)。那么你也有 tables 比如 ProductAttributeTypeProductAttribute.

基础 Product table 将包含所有产品共有的属性,例如 NamePrice.

ProductAttributeType

ProductAttributeTypeCode VARCHAR(10)
AttributeTypeName        VARCHAR(50)

其中 ProductAttributeTypeCode 包含属性类型的简短/缩写代码(例如 "BOOL"),而 AttributeTypeName 是友好名称(例如 "Boolean" 或 "Yes/No").

ProductAttribute

ProductId                INT          -- Foreign key to Product table
ProductAttributeTypeCode VARCHAR(10)  -- Foreign key to ProductAttributeType table
AttributeName            VARCHAR(100) -- The name of the product attribute (e.g. "Volume")
AttributeValue           VARCHAR(MAX) -- Contains the actual value of the product attribute

ProductProductAttribute是一对多关系。

这是我过去以及当前项目中采用的方法,并且效果很好。这似乎是解决此类问题的一种非常普遍的方法。我唯一能想到的 "downside" 是您需要确保 ProductAttribute.AttributeValue 列中的值与 ProductAttributeType(Code) 的适当类型相匹配。如果你的代码设计得当,并且经过深思熟虑,在我看来,它真的还不错。