将 属性 动态添加到 entity framework 对象

Dynamically adding a property to an entity framework object

我有一个 class 这样的:

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 模型,但性能不佳

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

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

您的 class 可以包含一个 ExtraPropertiesElement,它采用 XML 字符串,并将其解析为 XElement,然后您可以使用 XPath 来查询请求的 xml element/attribute。

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

您可以阅读有关 XML 数据类型及其用途的更多信息 here
您还可以阅读如何查询 XML 列存储 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(); }
    }
}