이 질문에 대해 Linq2SQL과 동등한 DbLinq를 사용하고 있습니다. 런타임에 반환 할 열을 지정하는 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));
아마도 누군가가 더 깨끗한 방법을 알고 있습니까?
해결책은 다음과 같습니다.
string someProperty = "phonenumber";
PropertyInfo property = typeof(T).GetProperty(propertyName);
string id = "1234";
Table<MyClass> table = context.GetTable<MyClass>();
Expression<Func<T, Object>> mySelect = DynamicExpression.ParseLambda<T, Object>(property.Name);
var query = (from asset in table where asset.Id == id select asset).Select(mySelect);
return query.FirstOrDefault();
솔루션의 역동적 인 측면은 리플렉션을 사용하도록합니다. 첫 번째 항목을 가져 와서 형식을 읽는 대신 IQueryable의 "ElementType"속성을 사용할 수 있습니다. 그런 다음 이와 같은 루프가 더 나을 수 있습니다.
var result = (from item in table where item.Id == id select item).Select("new (" + someProperty + ")");
PropertyInfo resultProperty = result.ElementType.GetProperty(someProperty);
foreach (var resultObj in result)
{
var value = resultProperty.GetValue(resultObj, null);
}
이 작업 중 일부를 수행하는 함수를 만들지 못해 개선해야 할 부분이 많지 않습니다. 컴파일러는 동적이기 때문에 객체의 내용을 알지 못합니다. 따라서 비 반사 코드의 모든 장점은 사용할 수 없습니다.