How to bind a field in Linq based on a dynamic field name

First of all, apologies for the poor title of the question - I'm not quite sure that I am asking the right thing.

I can usually do the following to access the field:

MyTables table = dc.MyTables.SingleOrDefault(p => p.id == someId); somevalue = table.samplefield; 

In this case, the variable somevalue will have the value of the field of the field field.

Now I have a scenario where I want to populate a variable, but I do not know the table field name at design time. However, I have this field name in the string. So you can get the value using this line?

Hoping this makes sense!

+6
c # linq
source share
5 answers

You need to use reflection, for example: (Untested)

 somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null); 
+5
source share

If you have string s = "sampleField"; , you can just use reflection:

 object value = table.GetType().GetProperty(s).GetValue(table, null); 

If you need PKID as a string, it is more complex, and you need to use the lambda generated during operation. Just how little it depends on the implementation - for example, to identify PK from LINQ-to-SQL, see this answer , which examines the metadata of context data.

+3
source share

To do this, you will need to use reflection.

 public object GetField(object obj, string fieldName) { var t = obj.GetType(); var field = t.GetField(fieldName); return field.GetValue(obj); } somevalue = GetField(table, "someFieldName"); 

This works as long as the field is instance and public. You will need to slightly modify the GetField method if accessibility was less than public.

+2
source share

This is definitely doable, but getting a lot harder. If you want to execute a fully dynamic LINQ query, you must check these messages by Scott Hanselm.

+2
source share

It’s strange that I just read something similar on Scott Hanselman’s blog, to establish where or to sort by the name of the field in the row, but I think that the selection can be made in the same way. Cm:

http://www.hanselman.com/blog/TheWeeklySourceCode48DynamicQueryableMakesCustomLINQExpressionsEasier.aspx

The kernel looks something like this:

 Dim Northwind As new NorthwindDataContext Dim query = Northwind.Products .Where("CategoryID=2 And UnitPrice>3") .OrderBy("SupplierID") GridView1.DataSource = query GridView1.DataBind() 

This may require some reference to dynamic data.

+2
source share

All Articles