Dimitri Sorokin
Dimitri Sorokin

Reputation: 19

Complex class hierarchies in C#

I have to create the class model which will contain 4 classes - Database, Schema, Table and Column, something like:

public class Database
{
    public string Name { get; set; }

    public List<Schema> Schemas { get; set; };
    public List<Table> Tables { get; set; };
    public List<Column> Columns { get; set; };
}

public class Schema
{
    public string Name { get; set; }

    public Database Database { get; set; }
    public List<Table> Tables { get; set; };
}

public class Table
{
    public string Name { get; set; }

    public Schema Schema { get; set; }
    public List<Column> Columns { get; set; };
}

public class Column
{
    public string Name { get; set; }

    public Schema Table { get; set; }
}

Well, the class hierarchy is pretty easy: Database->Schemas->Tables->Columns

As you can see there are the "Tables" and "Columns" - lists in the Database - class which should contain all tables and all columns in the database.

What is the better way to synchronize the Database.Tables - list and the Schema.Tables - list? And the Database.Columns and Table.Columns lists? It should be possible to add a new table to the Database.Tables and to see the new table in the according Schema.Tables - list. Or to add a new table to the Schema.Tables and see new table in the Database.Tables list.

I can define the Schema.Tables property as:

    public List<Table> Tables
    {
        get { return Database.Tables.Where(p => p.Schema == this).ToList<Tables>(); }
    }

But in this if I add new table to the Schema.Tables it will not appear in the Database.Tables list.

What is the better way to solve this problem?

PS. Sorry for my terrible English!

Upvotes: 1

Views: 346

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100630

Storing data in multiple places and then trying to synchronize them is one of the two hard problems in computer science (naming, off-by-one errors, and cache invalidation).

Unless you need actual lists in Database just enumerate them:

public class Database
{
    public string Name { get; set; }

    public List<Schema> Schemas { get; };

    public IEnumerable<Table> Tables 
    { 
         get { return Schemas.SelectMany(s=>s.Tables); }
    }

    public IEnumerable<Column> Columns 
    { 
      get { return Tables.SelectMany(t=>t.Columns); }
    }
}

Upvotes: 5

Related Questions