How can I do something like this:
var result = db.MyTable.Where(x => x."MyProperty" == "Test" );
As you can see I want to access "MyProperty" but give the property name as a sting.
How can I do something like this:
var result = db.MyTable.Where(x => x."MyProperty" == "Test" );
As you can see I want to access "MyProperty" but give the property name as a sting.
You could use reflection
although this might work, i wouldn't advise on doing this, why don't pass in your where clause as an expression like:
example after comment:
consider the following type:
you see there are three properties where the name is of type string and id is of type int. now if we wrap our database context in a service like this
in our get method there is an Expression parameter that takes two generics, the first is our type x and the second is a boolean. The advantage of this approach is that we can abstract all the data context creation and only express an where clause in our code see final piece of code:
as you can see, we can build a where clause on any property or combination of properties.
I think you can try this:
It works fine for order.
You can use reflection to get it unless you are querying a database directly using LINQ to SQL.
Here is a sample of how to get property info using reflection:
Just be careful because this could lead to performance issues if you are querying a large amount data.
I don't know how x is implemented, but if x has an indexer, then you could formulate your query like:
see http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx for indexers in c#