views:

10

answers:

0

I have an attribute table like the following

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

i then have the product attribute tables

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

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

For saving product attributes i use this code

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;
                }
            }
        }

and to get a products attribute value i use this code

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

I find myself repeating this case statement in a few different places and would like to know how i could replace it using polymorphism?