使用多态性从EAV表结构中保存和检索

时间:2010-09-29 14:39:19

标签: polymorphism entity-attribute-value

我有一个属性表,如下所示

Attributes
attributeid   backendtype   code            displayname
1             int           size            Product Size
2             text          description     Product Description

然后我有产品属性表

ProductAttributes_ints
id     attributeid          productid       value(int)
1      1                    1               20

ProductAttributes_texts
id     attributeid          productid       value(text)
1      2                    1               my product description

为了保存产品属性,我使用此代码

public void SaveAttribute(int productId, int attributeId, string backendType, string value)
        {
            if (!String.IsNullOrEmpty(value))
            {
                switch (backendType)
                {
                    case "int":
                        int valueInt = Convert.ToInt32(value);
                        SaveAttributeInt(productId, attributeId, valueInt);
                        break;
                    case "text":
                        SaveAttributeText(productId, attributeId, value);
                        break;
                    case "decimal":
                        decimal valueDecimal = Convert.ToDecimal(value);
                        SaveAttributeDecimal(productId, attributeId, valueDecimal);
                        break;
                    case "varchar":
                        SaveAttributeVarchar(productId, attributeId, value);
                        break;
                    default:
                        break;
                }
            }
        }

并获取产品属性值我使用此代码

public string GetProductAttributeValue(string code)
        {
            Attribute attribute = _attributeRepository.GetAttributeByCode(code);

            if (attribute != null)
            {
                switch (attribute.BackendType)
                {
                    case "int":
                        var productAttributeInt = this.ProductAttributes_ints.Where(a => a.Attribute.Code == code).FirstOrDefault();
                        if (productAttributeInt != null)
                        {
                            if (productAttributeInt.Value != null)
                            {
                                return productAttributeInt.Value.ToString();
                            }
                            else
                            {
                                return null;
                            }
                        }
                        else
                        {
                            return null;
                        }
                        ... repeated for all other datatypes

我发现自己在几个不同的地方重复这个案例陈述,并想知道我如何用多态来取代它?

0 个答案:

没有答案
相关问题