Paweł Hemperek Paweł Hemperek - 11 months ago 44
C# Question

Flexible properties mechanism

Let's say I have a class called

. I can add various types of car related expenses - tank expenses, repair expenses, tickets etc. Some properties of expense are the same for all types like cost, date etc., but there are some differences. For example: when I fuelled my car I want to save information like did I fully filled up my tank or not. However when I'm saving repair I want to save some other info.

The problem is - how to create some sort of flxible properties mechanism?

What I came up with is to have two tables:
. In
table I could store all basic, common data and
would have following structure:

| Id | PropertyName | PropertyValue | ExpenseId
| 1 | IsFull | "true" | 1
| 2 | Stuff | "2016-10-02" | 1

The problem is, for
column I would have to use specific type, like
for example. In this case, I wouldn't be able to sort those values correctly (eg. by date)? Or maybe I would?

I think that there has to be a better way to do this using Entity Framework Code First approach.

Answer Source

I would create your class/object model first (rather than the other way around, i.e., starting with the database):

public abstract class ExpenseBase 
    public DateTime ExpenseDate { get; set; }
    public double Cost { get; set; }

public class FuelExpense : ExpenseBase
    public  Boolean FilledUp { get; set; }

public class OtherExpense : ExpenseBase
    public string SomeOtherProperty { get; set; }

Then choose an inheritance mapping strategy. I usually go with Table Per Type (TPT) in this situation.