Pouring table <T> into something
I have a datacontext and it has a table of authors.
public partial Author:IProductTag{} I want to add a Table<Authors> object to a Table<IProductTag> , but this seems impossible. I am trying to do this because I want my method to be able to work with different tables that are included as input parameters. To be more specific, I need to execute the OrderBy and Select table methods. I have several other tables whose entities implement IProductTag. In addition, I tried to write a function such as:
public static void MyF<t>(){ Table<t> t0 = (Table<t>)DataContext.GetMyTableUsingReflection(); } But this fails at compile time. And if I draw the table with something like ITable or IQueriable, then the OrderBy and Select functions just don't work. So how do you deal with this?
I suspect you want to make your general method - so instead
void DoSomethingWithTable(Table<IProductTag> table) you should have
void DoSomethingWithTable<T>(Table<T> table) where T : class, IProductTag This should work fine, assuming you only need to read objects (and apply operator queries, etc.). If this does not work for you, please give more details on what your method should do.
(You say that your attempt to use reflection failed, but you did not say how it failed. Could you give more details?)
I have no idea what ProductTag , so I used different types to show my solution to this problem. Yes, there seems to be no way to get a Table<T> , but you can get an IQueryable<T> that works just as well (at least for my situation).
I have a simple analytics database, where each website has its own table containing both general and specific elements. I wanted to use the interface for shared data.
public interface ISession { public DateTime CreateDt {get; set; } public string HostAddress {get; set; } public int SessionDuration {get; set; } } public static IQueryable<ISession> GetQueryableTable(MyDataContext db, string site) { Type itemType; switch (item) { case "stackoverflow.com": itemType = typeof(Analytics_StackOverflow); break; case "serverfault.com": itemType = typeof(Analytics_ServerFault); break; default: throw Exception(); } return db.GetTable(itemType).Cast<ISession>(); } Then you can execute this query:
var table = GetQueryableTable(db, "stackoverflow.com"); var mySessions = table.Where(s => s.HostAddress == MY_IP); To create a new line, you can use reflection:
var rowType = typeof(Analytics_ServerFault); var newRow = (ISession) rowType.GetConstructor(new Type[0]).Invoke(new object[0]); (I have a function to get GetRowType - which is not shown here).
Then to insert into the table, I have a separate helper function:
public static void Insert(MyDataContext db, ISession item) { // GetTable is defined by Linq2Sql db.GetTable(GetRowType(domain)).InsertOnSubmit(item); }