Dynamically adding a property to an entity framework object

被刻印的时光 ゝ 提交于 2020-08-03 05:49:13

问题


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:


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


来源:https://stackoverflow.com/questions/30783224/dynamically-adding-a-property-to-an-entity-framework-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!