tags:

views:

50

answers:

2

I'm working with a 14-year old schema where a parent table (P) contains a type (8 possibilities) and location (3 possibilities) field that together point to one of twenty-four specific tables (A1, A2, A3, B1, B2, B3...), all with identical schemas for their type.

I would like to create a generic way to access the specific tables but cannot seem to make it work.

Let's say the parent table is called Document and two types of specific are (NewLetter, CurrentLetter, and HistoricLetters) and (NewBill, CurrentBill, and HistoricBills).

 public interface ILetter
 {
     DateTime CreationDate { get; }
 }

 public interface IBill
 {
     DateTime BillDate { get; }
 }

 // The LINQ 2 SQL generated classes already implement the CreationDate property
 public partial class NewLetter : ILetter { }
 public partial class CurrentLetter : ILetter { }
 public partial class HistoricLetter : ILetter { }

Then in my code, I would like to be able to do this:

 switch (type)
 {
   case 1:
     Table<IBill> specificBill;
     switch (location)      
     {
        ...
     }

   case 2:
     Table<ILetter> specificTable;
     switch (location)
     {
       case 1: specificTable = dataContext.NewLetter as Table<ILetter>; break;
       case 2: specificTable = dataContext.CurrentLetter ...
       case 3: specificTable = dataContext.HistoricLetter ...
      }   
 }

Or something similar. Unfortunately I can't cast Table<NewLetter> to Table<ILetter> even if NewLetter implements ILetter. Is there any way around this? I guess I'm basically trying to create a view in C#, as I don't have the permissions to create one in the db itself.

A: 

Look at inheritance in Linq2SQL. Your tables will need some kind of discriminator column/property.

leppie
Will that work for the updated example? It looks like I have to switch off two fields instead of just one.
Jedidja
I've read about inheritance and it's definitely not the way to go for this situation. I suppose using Dynamic LINQ might work with GetTable() and then executing the commands against that.
Jedidja
+1  A: 

The DataContext has a generic method to retrieve the table you want:

var table = dataContext.GetTable<NewLetter>();

Maybe you could use that to rewrite your query:

var table = dataContext.GetTable<NewLetter>();
var letters = 
    from letter in table
    where ...
    select letter as ILetter;
Thomas Eyde