What is the best way to enforce properties that must be implemented at each subclass in *different* fields?

I am trying to come up with the "best" way to implement SQL Data Services flexible entity model where each class could be stored as an entity, even derrived classes.

Example: Every subclass has different

string Id
string Kind
Dictionary<string, object> Properties

So far, I'm heading in the direction of having both an Entity class (with above) and a base class that has some kind of collection like

Dictionary<string, Entity> data

And have each subclass add to that dictionary and just get/set properties like

data["EntityKind"].Properties["PropertyName"]

However, since each class only has ONE Entity, it seems like I should be using some sort of Stack (intead of Dictionary) where each level of the hierarchy knows exactly where it is. Then it occured to me that class inheritance IS the stack, so I thought maybe I was just missing some huge OO concept that would really simplify all of this. Something like

abstract eachsubclassmusthaveitsown Entity entity

Upvotes: 3

Views: 272

Answers (1)

Daniel Earwicker
Daniel Earwicker

Reputation: 116684

Each class is an entity, and you want to associate some entity metadata with it?

It sounds like Attributes might be your best shot.

You would define a class EntityAttribute, with members to store the metadata needed to describe an entity. That would then allow you to tag entity classes with [Entity]. If all the fields are mandatory, give the attribute class a single constructor that requires the values to be passed.

Then use reflection to discover the entity classes. Note that you only need to do that discovery process once and then cache it, so the performance of reflection should not be an issue.

Upvotes: 3

Related Questions