7

Firstly, apologies for the bad question title - not entirely sure if I am asking the correct thing.

Normally I can do the following to access a field:

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

In this instance the variable somevalue would end up having the value of the field samplefield.

Now I have a scenario where I want to populate a variable, but I don't know the name of the table field at design time. I do however, have this fieldname in a string. Is it therefore possible to fetch a value using this string?

Hoping this makes sense!

Martin
  • 38,157
  • 20
  • 98
  • 129

5 Answers5

6

You need to use reflection, like this: (Untested)

somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null);
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
3

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

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

If you need the PKID as a string, it is more complex, and you need to use a runtime-generated lambda. Exactly how depends slightly on the implementation - for example, to identify the PK from LINQ-to-SQL, see this answer which looks at the data-contexts metadata.

Community
  • 1
  • 1
Marc Gravell
  • 976,458
  • 251
  • 2,474
  • 2,830
3

Weirdly I have just been reading something similar on Scott Hanselman's blog, this is to set the where or ordering by a field name in a string but I think the select could be done in the same way. See:

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

The core being something like :

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

It may require some dynamic data references.

PeteT
  • 17,725
  • 26
  • 91
  • 132
2

In order 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 both instance and public. You'd need to modify the GetField method call slightly if the accessibility was less than public.

JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
2

It is definitely doable but does get alot more complicated. If you want to do a completely dynamic LINQ query you should check out these posts by Scott Hanselman.

smaclell
  • 4,478
  • 7
  • 41
  • 49
  • After seeing all of the responses I definitely missed the boat. LINQ is not required for this scenario at all. The reflection methods shown here are exactly what you need. – smaclell Jan 27 '10 at 16:01