G
G
georgich2020-01-31 13:45:59
OOP
georgich, 2020-01-31 13:45:59

How to use static property from child class?

Greetings!
There is the following code:

public abstract class ActiveRecordEntity
    {
        protected int Id { get; set; }

        protected static string TableName { get; }

        public static DataTable DataTable
        {
            get
            {
                var schemaTable = new DataTable { Locale = CultureInfo.InvariantCulture };
                
                var dataAdapter = new SQLiteDataAdapter
                {
                    SelectCommand = new SQLiteCommand("SELECT * FROM " + TableName + ";", Database.Connection)
                };

                dataAdapter.Fill(schemaTable);

                return schemaTable;
            }
        }
    }
    public class Category : ActiveRecordEntity
    {
        public string Title { get; set; }
        protected static string TableName => "category";
    }

It is necessary for me that in the base class the property with the name of the table from the child class gets into the TableName property. So far, it has not been implemented. Tell me, please, how to be? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-01-31
@georgich

I would refrain from using global state. If you really need one instance, then create it explicitly at the root of the application and reuse or delegate this responsibility to the IoC container.
Implementation without global variables:

public abstract class ActiveRecordEntity
    {
        protected int Id { get; set; }

        public readonly string TableName;
        public DataTable DataTable { get; }

        public ActiveRecordEntity(string tableName, SQLiteConnection connection)
        {
            TableName = tableName;
            DataTable = new DataTable { Locale = CultureInfo.InvariantCulture };
            var dataAdapter = new SQLiteDataAdapter
            {
                SelectCommand = new SQLiteCommand($"SELECT * FROM {TableName}", connection)
            };

            dataAdapter.Fill(DataTable);
        }
    }
    public class Category : ActiveRecordEntity
    {
        public string Title { get; set; }
        public Category(SQLiteConnection connection) : base("category", connection)
        {
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question