【发布时间】:2021-09-28 14:55:54
【问题描述】:
我正在尝试根据排序方向动态创建 orderby
public class Item
{
public Guid ItemId {get; set;}
public string ItemName { get; set; }
public List<ItemProductType> ItemProductTypes {get; set;}
}
public class ItemProductType
{
public Guid ItemId {get; set;}
public Guid ProductTypeId {get; set; }
public Item Item { get; set; }
public ProductType ProductType { get; set; }
}
public class ProductType
{
public Guid ProductTypeId {get; set;}
public string ProductTypeName { get; set; }
public List<ItemProductType> ItemProductTypes {get; set;}
}
我需要在 item 表上创建一个 orderby 语句,例如
_context.Items.Include(a => a.ItemProductTypes)
.ThenInclude(a => a.ProductType)
.OrderBy(a =>
a.ItemProductTypes.OrderBy(b => b.ProductType.ProductTypeName)
.Select(c => c.ProductType.ProductTypeName)
.FirstOrDefault()
).ToListAsync();
以上代码可以正常工作,但我需要根据来自 ColumnHeader 单击的 Sortdirection 升序或降序来更改顺序。
我尝试在 Queryable 上使用 OrderBySortDynamic 扩展方法来动态获取 orderby 或 orderbydescending
public static IQueryable<t> OrderBySortDynamic<t, TKey>(this IQueryable<t> query, Expression<Func<t, TKey>> keySelector, bool sortDescending)
{
string command = "OrderBy";
if (sortDescending)
{
command = "OrderByDescending";
}
Expression resultExpression = Expression.Call(
typeof(Queryable),
command,
new[] { typeof(t), keySelector.ReturnType },
query.Expression,
Expression.Quote(keySelector));
return query.Provider.CreateQuery<t>(resultExpression);
}
如何创建扩展方法以在子导航属性上动态执行 orderby,其中 a.ItemProductTypes.OrderBy(b=>b.ProductType.ProductTypeName)。我尝试使用 Ienumerable 更新上述扩展方法,但它不起作用。
【问题讨论】:
-
在没有动态实现的情况下编写工作查询。目标很难理解。
-
我需要根据navigationproperties(itemtype) child(type.typename)对父实体(item)进行排序,并且需要动态地进行排序
-
显示工作的非动态查询。
-
_context.Items.Include(a => a.ItemProductTypes) .ThenInclude(a => a.ProductType) .OrderBy(a => a.ItemProductTypes.OrderBy(b => b.ProductType. ProductTypeName) .Select(c => c.ProductType.ProductTypeName) .FirstOrDefault() ).ToListAsync();这个 linq 正在工作
-
这个查询甚至不能编译,也不会工作。使用有效的非动态查询更新问题并显示哪个部分应该是动态的。
标签: c# linq lambda entity-framework-core expression-trees