Search code examples
c#wpfgeneric-collections

C# Generic Table from DataContext


I'm attempting to create a generic WPF form or page, that when called, will load in data from a LINQ table. Here is the concept:

I have three tables in a LINQ DataContext that are identical (apart from the data within)

TypeID and Type are the columns

I would like to generically pass that data in those tables into my second form depending on which table the user selects (essentially so they can narrow down the list of objects of said Type.

I've seen some responses, (in particular the accepted answer to this one LINQ query with a generic table) that are very close to what I am looking for, but not quite. One issue I have with the above answer is that T must be a reference type.

I've done more searching and found some more answers like:

someClass<T> : <T> where T

But unfortunately these are further from my own context and I am unable to bridge the two concepts of what is happening. Below I have posted what I hope to do.

someDataContext db = new someDataContext();

private void pageLoader<T>(){
    newPage n = new newPage(T) //This is where I was hoping I could pass the table(s) to the constructor.
}

And here is the constructor:

newPage(T){
    listBox l = new listBox();
    l.datasource = T;
}

Any assistance in any direction would be helpful (besides MSDN, please. I've been there and I'm still lost.)


Solution

  • Let start from the top. LINQ is merely an abbreviation for Language Integrated Query. It is interchangeable with Lambda. Different syntax but both accomplish the same task. Querying a collection or datasource. See http://msdn.microsoft.com/en-ca/library/bb397926.aspx

    You are referring to the EntityFramework Code First approach of creating a database. LINQ is merely a way to access and manipulate the information within.

    With that out of the way, what you are pointing out is a Generic Method and a Generic Class. T is simply a standard naming convention for a generic type. You could use any representation you like. If you are going to be passing in entities, you might use TEntity for example.

    See http://www.dotnetperls.com/generic-method http://www.dotnetperls.com/generic

    When you see someClass where T, this is a constraint for type parameters.

    And finally, what you have been waiting for...

    https://codereview.stackexchange.com/questions/19037/entity-framework-generic-repository-pattern

    The following should put you on the right path.

    http://blog.gauffin.org/2013/01/repository-pattern-done-right/ <- This would be more of a better starting tutorial