How do I reference a field in Linq based on a dynamic fieldname
Firstly, apologies for the bad question title - not entirely sure if I am asking the correct thing.
Normally I can do t开发者_如何学编程he 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!
You need to use reflection, like this: (Untested)
somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null);
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.
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.
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.
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.
- The Weekly Code Sample 48 - DynamicQueryable makes custom LINQ expressions easier
- The Weekly Code Sample 47 - ASP.NET 3.5 Dynamic Data: FilterRepeaters and Dynamic Linq Query Generation
精彩评论