开发者

C#: access a class property when the property identifier is known as a string

开发者_Go百科

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 :(


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.


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


http://msdn.microsoft.com/library/system.reflection.fieldinfo(VS.90).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜