Dynamically adding a property to an entity framework object

3.1k views Asked by At

I have a class like this:

public class Empresa 
{
    public string Nombre { get; set; }
    public string NIT { get; set; }
    public string NombreRepresentanteLegal { get; set; }
    public string TelefonoRepresentanteLegal { get; set; }
    public string NombreContacto { get; set; }
    public string TelefonoContacto { get; set; }
}

However in my app, I want the users to be able to add custom properties, for example twitter handle, however I havent found documentation in how to do that, I heard about the EAV model, but thats not performant

1

There are 1 answers

0
Michael G On BEST ANSWER

You could store the additional data as XML into an XML column, and have the client deserialize / serialize the meta-data appropriately. Xml can be a viable solution for when you don't know the structure of the data, or if the structure can be altered at run-time.

You're also able to INDEX the XML to help with shredding / querying, so performance can be maintained while processing large xml documents.

Your class could contain, an ExtraPropertiesElement, that takes the XML string, and parses it into an XElement, which you could then utilize XPath, to query for the requested xml element/attribute.

One problem with this approach, is that all additional properties are stored in XML in the database, and it's not as easy to perform queries against the data. It's straightforward to do so, but it's not as simple as selecting a column name from a table.

You can read more about the XML Data Type and the uses here.
You can also read up on how to query XML column stores here.

public class Empresa 
{
    public string Nombre { get; set; }
    public string NIT { get; set; }
    public string NombreRepresentanteLegal { get; set; }
    public string TelefonoRepresentanteLegal { get; set; }
    public string NombreContacto { get; set; }
    public string TelefonoContacto { get; set; }

    [Column(TypeName="xml")]
    public string ExtraProperties { get; set; }

    [NotMapped]
    public XElement ExtraPropertiesElement
    {
        get { return XElement.Parse(ExtraProperties ); }
        set { ExtraProperties = value.ToString(); }
    }
}