简体   繁体   English

支持用户定义的数据库字段的动态类

[英]Dynamic Class To Support User-Defined Database Fields

I'm currently developing a WCF service in C# to serve as a basic API for an existing internal app. 我目前正在使用C#开发WCF服务,以用作现有内部应用程序的基本API。 The API I'm developing specifically focuses on adding and deleting records from the database. 我正在开发的API特别专注于在数据库中添加和删除记录。

However, the application allows the end-user to alter the existing database structure by adding custom fields in each table. 但是,该应用程序允许最终用户通过在每个表中添加自定义字段来更改现有数据库结构。

This means that one departments' CUSTOMER table may look like this: 这意味着一个部门的CUSTOMER表可能如下所示:

Id | FirstName | LastName | City | State | FavColor

While another departments' CUSTOMER table looks like this: 而另一个部门的CUSTOMER表如下所示:

Id | FirstName | LastName | City | State | FavFood | FavMovie

How would I design a class to support the user-defined (Fav) fields given the structure above? 给定上述结构,我将如何设计一个类来支持用户定义的(Fav)字段?

I considered using a Dictionary to handle the user-defined fields: 我考虑过使用Dictionary处理用户定义的字段:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public Dictionary<string, string> UserDefinedFields { get; set; }
}

Is there a better (ie more established/best practice) for handling this requirement? 是否有更好的方法(即更成熟的/最佳实践)来处理此要求?

If the user defined fields were bounded you may well be served with inheritance using a type descriminator as a field. 如果用户定义的字段是有界的,则可以使用类型说明符作为字段来继承继承。 I'll dig out a Martin Fowler article for this. 为此,我将挖掘Martin Fowler的文章。 However, for extensibility using a vertical table (known as Entity Attribute Value) I have done something similar in the past. 但是,为了使用垂直表(称为“实体属性值”)进行扩展,我过去做过类似的事情。 It worked just fine. 工作正常。

EDIT: It just occured to me that you could also serialize the instance and add it as a blob/text to a persistence medium. 编辑:对我来说,您还可以序列化实例并将其作为Blob /文本添加到持久性介质中。 That way you can be fairly lax about schema. 这样,您就可以对架构相当放松。 I think a document DB like Mongo would be good for this type of thing or a BLOB field in MSSQL 我认为像Mongo这样的文档数据库适合这种类型的事情或MSSQL中的BLOB字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM