Search code examples
c#inheritancecode-firstinstantiationdiscriminator

Child class instantiation, automatically set the discriminator property for me (Code First)


I have a parent abstract class:

public abstract class Transaction
{
    public int ID { get; set; }
    public string TransactionDescr { get; set; }
    public DateTime TransactionDate { get; set; }        
    public int TransactionType { get; protected set; }
}

And some real child classes that I want to set the TransactionType property when it instantiated.

In my database, I have a TransactionType column which I use as the discriminator.

This is my idea:

public class TransactAdd : Transaction
{
    public TransactAdd()
    {
        TransactionType = 1;
    }
}
public class TransactDeduct : Transaction
{
    public TransactDeduct()
    {
        TransactionType = 2;
    }
}
public class TransactTransfer : Transaction
{
    public TransactTransfer()
    {
        TransactionType = 3;
    }
}

Is it a good idea to set the TransactionType in class constructor?? am I right? or is there a better way?

By the way, finally, I save the parent class Transaction in the database using Dapper.

I add the solution, thanks to @flobjective

UPDATE(Solution)

public abstract class Transaction
{
    public int ID { get; set; }
    public string TransactionDescr { get; set; }
    public DateTime TransactionDate { get; set; }        
    public abstract int TransactionType { get; }
}

public class TransactAdd : Transact
{
    public override int TransactType
    {
        get
        {
            return 1;
        }
    }
}
public class TransactDeduct : Transact
{
    public override int TransactType
    {
        get
        {
            return 2;
        }
    }
}
public class TransactTransfer : Transact
{
    public override int TransactType
    {
        get
        {
            return 3;
        }
    }
}

Solution

  • One weakness of your solution is that you have to remember to set the transaction type. In case somebody else adds a new Transaction class he may forget and this will lead to a wrong TransactionType value of 1.

    Other than that intTransactionType has protected setter which means somebody could later change the type which could lead to problems.

    You could create an abstract method (Get)TransactionType that forces each concrete implementation to return an int. However that still does not ensure that you use unique integers for all types.