Polymorphism with Database Query

2019-08-28 06:29发布

问题:

I am designing a dashboard to display corporate metrics (currently with ASP.net 3.5 in C#), and looking for advice on design. I'm not as used to OOP in web applications.

There may be many different metrics that can be seen by different users in a Many-to-Many relationship. I am storing the users in a local SQL database and it of course makes sense to store the metadata for each "Metric" as well. This also provides a sort of access control list for each one. Each metric can have several different charts which have different designs (bars, columns, pies, lines, or combinations of those with different series on different y-axes, etc...).

These charts could be designed programmatically and then added to the ASP.net page at runtime. It would be nice to have an inheritance structure of a superclass of a blank chart and different chart types that extend that.

The page would select the charts the given user has the right to view and then generate those. Still, I'm seeing some kind of big switch statement as a crude lookup table for the appropriate subclass to instantiate based on the information selected in the database.

Is there a more artistic way to do this? Somehow supplying the type declaration at runtime? Should I move all the style information about the charts into the database and have additional tables and columns for series, datapoints, colors, etc, where a single chart class does all the necessary queries and builds a chart? Thanks.

回答1:

I realized what I'm looking for could be solved with dynamic class loading. There's a great example of dynamic class loading in C# here from Michael Clarke.

Basically I can load a class based on a string filename coming from a query.



回答2:

You could store the Strong name of the class in the DB and then simply create an instance of the class.

So instead of sorting that its a bar chart you might store something like

YourNamespace.UI.Charts.Bar

Personally I wouldn't be too scared of just storing a chart type though as it provides you with a layer of abstraction that may be helpful.