views:

91

answers:

3

Hi,

I'm using LINQ to Entities on a database which structure is not known in advance. I use reflection to retrieve the information, and now have a list of strings with all the table names. Because I use LINQ, I also have the datasource encapsulated in a C# class (linqContext), with each table being a property of that class.

What I want to achieve is this: Assume one of the strings in the table names list is "Employees". This is known in code, I want to do the following:

linqContext.Employees.DoSomethingHere();

Is this possible? I know that if all the propertie were just items in a list, I could use the string as indexer, linqContext["Employees"]. However, this is not the case :(

A: 

Use reflection to either retrieve the named property of the DataContext, or to retrieve the entity type and then call DataContext.GetTable(type).

devio
+2  A: 

Firstly I wouldn't use reflection to get this information, I would use the MetadataWorkspace property of the ObjectContext as this already has the information. Something like this:

EntityContainer container = context.MetadataWorkspace
    .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
var setNames = container.BaseEntitySets.Select(b =>b.Name);

Once you have the set names you can get the data from a specific set as follows:

context.CreateQuery<T>("[" + entitySetName + "]");

The generic repository I use actually searches the container for the entity set that matches a given type so that calling code can just pass the type in and get back the appropriate collection.

Mant101