NibblyPig
NibblyPig

Reputation: 52962

Access a property of a DbSet by name

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.

Upvotes: 9

Views: 11031

Answers (2)

MBender
MBender

Reputation: 5650

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();

Upvotes: 15

Tim B
Tim B

Reputation: 2368

Check out this article on Dynamic LINQ.

Using the provided code, I was able to write a LINQ to Entities query like this:

var query = context.Set(Type.GetType("Person")).Select("Name");

Upvotes: 6

Related Questions