我几乎搜索了我能找到的每个问题,博客或文档,以帮助我回答这个问题的答案。一些实际上帮助我更接近它,但我仍然没有解决它,因为大多数要么已经过时,要么没有真正与我需要的点。不要打扰告诉我关于表达式的事情,因为如果我采取更长的路线,我就不会使用这个库。
我的项目目标是通过使用泛型方法,仅使用表/列名称字符串和用于过滤的值来提供过滤和排序。长话短说,我有两个表,关系为1到n,基本上这样连接,我想按客户的名字订购:
public partial class Transactions{
public ICollection<Customer> customer { get; set; };
}
public partial class Customer{
public string name { get; set; };
}
到目前为止,我几乎需要实现我想要的,除了弄清楚如何正确构造OrderBy字符串,以一种我使用单个ICollection结果的方式。
到目前为止我的内容非常类似(对于我的文档过于冗长而感到抱歉):
using System.Linq.Dynamic;
using System.Reflection;
namespace com.betha.common
{
public class Filter
{
/// <summary>
/// Dictionary of codenames and column names populated by a different, specific class (properties.Add("customer", "tb_customer.name"))
/// </summary>
public Dictionary<string, string> properties;
public Filter(Dictionary<string, string> properties)
{
this.properties = properties;
}
/// <summary>
/// Generic method designed to filter and order using just lists of column names and values
/// </summary>
/// <typeparam name="T">Type of the first IQueryable</typeparam>
/// <typeparam name="T2">Type of the second IQueryable</typeparam>
/// <param name="query">IQueryable containing the results from the parent table (context.table1).AsQueryable();</param>
/// <param name="query2">IQueryable containing a single result from a descendant table (context.table2.Select(t2 => t2.field).FirstOrDefault()).AsQueryable();</param>
/// <param name="prop">Property codename that if used, matches a properties codename Key</param>
/// <param name="descend">Condition for ascending or descending results</param>
/// <returns>Ordered and/or filtered IQueryable</returns>
public IQueryable<T> FilterandOrder<T, T2>(IQueryable<T> query, IQueryable<T2> query2, string prop = null, string descend = null)
{
if (!String.IsNullOrEmpty(prop))
{
foreach (KeyValuePair<string, string> item in properties)
{
if (prop == item.Key)
{
prop = item.Value;
}
}
T2 subprop = query2.FirstOrDefault();
if (prop.Contains("."))
{
switch (prop.Split('.'))
{
default:
PropertyInfo property = subprop.GetType().GetProperty(prop.Split('.')[1]);
ParameterInfo[] index = property.GetIndexParameters();
object value = subprop.GetType().GetProperty(prop.Split('.')[1]).GetValue(subprop, index);
//This is the main issue, I have pretty much everything I should need, but I can't imagine how to write this OrderBy string properly.
//If I were to do it without the library: table.OrderBy(t => t.table2.Select(t2 => t2.field).FirstOrDefault());
//Without ordering by an ICollection property, like in the else below, string should look like: "field".
//Or in case of a 1 to 1 relationship, "table2.field".
query = DynamicQueryable.OrderBy(query, prop + (descend == "dec" ? " descending" : ""), value);
break;
}
}
else
{
query = DynamicQueryable.OrderBy(query, prop + (descend == "dec" ? " descending" : ""));
}
}
return query;
}
}
}
答案 0 :(得分:2)
您可以使用支持的功能t => t.table2.Select(t2 => t2.field).FirstOrDefault()
替换Min()
:
OrderBy("table2.Min(field)");