在调用Linq-To-Entities时可以做这样的事情吗?
// Makes a call to the database getting a list of people
public Person[] GetPeople(string sortBy) {
var people = context.Persons.AsQueryable();
// Determining which private method to call for sorting
var sortBy = null;
switch (sortBy) {
case "name":
sortBy = SortByName; // Should this actually execute the function? Or just be a reference to the function?
break;
case "age":
sortBy = SortByAge;
break;
case "hairColor":
sortBy = SortByHairColor;
break;
}
// Return sorted results
return people.OrderBy(sortBy).ToArray();
}
// Sorting by the person's name
private WHATGOESHERE SortByName() {
return q => q.Name;
}
// Sorting by the person's age
private WHATGOESHERE SortByAge() {
return q => q.DateOfBirth;
}
// Sorting by the person's hair color
private WHATGOESHERE SortByHairColor() {
return q => q.HairColor;
}
我需要将它们分开的原因是因为我有多个方法,不同的逻辑返回不同的人子集。并且,在每种方法中,我都有条件逻辑来确定排序。我似乎经常复制排序逻辑。
我还希望能够通过多种方法进行排序,例如:
people = people.OrderBy(SortByName).ThenBy(SortByAge).ThenByDescending(SortByHairColor);
我找到了this thread,但我无法让它发挥作用。
感谢任何帮助。
编辑#1:我忘了提到我对动态查询不感兴趣,如:
.OrderBy("Name, DateOfBirth, HairColor DESC");