Access a property of a DbSet by name

c#, entity-framework

Solution

I did something similar a while back using reflection.

T item = context.Set(T).First();
string propName = "MyProperty";
object value = item.GetType().GetProperty(propName).GetValue(item, null);

Of course note that you'll either need to cast the values to a specific type manually, or use `ToString`, which should work quite well on all basic types.

This assumes you already have the data from the server, and now need to process it.

EDIT:

If you want to create a query, then I found this!

Apparently, what you're looking for is available as part of Entity Framework these days.

An extension method is available which allows you to use `.Select("propertyName")` which returns `IQueriable`. Remember to add `System.Linq.Dynamic` to your `using` section.

You can then create select queries by specifying the name of the parameter.

List<object> data = (db.Set<SetType>()
                       .Where("propertyName == @0 && someOtherProperty == @1", propertyValue, someOtherPropertyValue)
                       .Select("propertyName") as IEnumerable<object>).ToList();

Problem

I have a `DbSet<T>` I want to access one of the properties on it by name. Is this possible? I'm basically making a generic function, so that for any DbSet I have, I can specify a column and have it list the values of that column. You can get the `DbSet` itself from the context by doing `context.Set(T)` but I am not sure about the fields.

Original source