Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 384
NibblyPig Avatar asked Jul 25 '13 11:07

NibblyPig


2 Answers

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();
like image 181
Shaamaan Avatar answered Oct 17 '22 09:10

Shaamaan


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");
like image 22
Tim B Avatar answered Oct 17 '22 07:10

Tim B