我正在使用 DbLinq,对于这个问题,它应该等同于 Linq2SQL。我需要生成一个 Linq2SQL 查询,在其中指定要在运行时返回的列。我可以使用 Dynamic Linq 扩展方法来实现这一点,但我不知道如何提取结果。
string someProperty = "phonenumber";
string id = "1234";
Table<MyClass> table = context.GetTable<MyClass>();
var queryResult = (from item in table where item.Id == id select item).Select("new (" + someProperty + ")");
Linq 表达式生成正确的 SQL:
select phonenumber from mytable where id = '1234'
在调试器中,我可以在结果视图中看到 phonenumber 值。问题是我不知道如何从 queryResult 对象中获取 phonenumber 值?queryResult 的类型是:
QueryProvider<DynamicClass1>
编辑:我发现了一种方法,但它看起来很粗糙。
IEnumerator result = (from item in table where item.Id == id select item).Select("new (" + someProperty + ")").GetEnumerator();
result.MoveNext();
var resultObj = result.Current;
PropertyInfo resultProperty = resultObj.GetType().GetProperty(someProperty);
Console.WriteLine(resultProperty.GetValue(resultObj, null));
也许有人知道更清洁的方法?