将属性动态添加到实体框架对象 [英] Dynamically adding a property to an entity framework object

查看:58
本文介绍了将属性动态添加到实体框架对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的课程:

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

但是在我的应用程序中,我希望用户能够添加自定义属性(例如twitter句柄),但是我还没有找到有关该方法的文档,听说过EAV模型,但那不是很有效

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

推荐答案

您可以将其他数据作为XML存储到XML列中,并让客户端适当地反序列化/序列化元数据。当您不知道数据的结构或在运行时可以更改结构时,Xml可能是一个可行的解决方案。

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.

能够对XML进行索引以帮助进行分解/查询,因此在处理大型xml文档时可以保持性能。

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

您的类可以包含一个ExtraPropertiesElement,它采用XML字符串,并将其解析为XElement,然后您可以利用XPath查询所请求的xml元素/属性。

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.

此方法的一个问题是,所有其他属性都存储在数据库中的XML中,并且对数据执行查询并不容易。这样做很简单,但没有从表中选择列名那么简单。

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.

您可以阅读有关XML数据类型及其用法的更多信息此处

您还可以阅读有关如何查询XML列存储的信息此处

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

这篇关于将属性动态添加到实体框架对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆