【发布时间】:2017-08-24 07:10:41
【问题描述】:
我是 Entity Framework 和 linq 的新手。我正在使用 asp.net mvc 5 和 C#。 我写了一个动态排序的查询如下:
public static IEnumerable<T> OrderByDynamic<T>(this IEnumerable<T> source, string propertyName, bool Ascending)
{
if (Ascending)
return source.OrderBy(x => x.GetType().GetProperty(propertyName).GetValue(x, null));
else
return source.OrderByDescending(x => x.GetType().GetProperty(propertyName).GetValue(x, null));
}
在我的存储库中我可以写:
string sortExpr = "name";
_objDB.hotels.Where(s => (s.city_id = 1))
.OrderByDynamic(sortExpr, Ascending).ToList();
当对表的列进行排序时,此代码可以正常工作,但我需要通过 SQL 函数进行排序。我使用以下代码将函数输入到.edmx 模型中
[EdmFunction("hotelReservation.Core.Data", "getHotelMinPrice_cap")]
public static int getHotelMinPrice_cap(int Hotel_id, int capacity, DateTime enter_date, DateTime exit_date)
{
throw new NotSupportedException("Direct calls are not supported.");
}
我的 SQL 选择类似于:
select *
from hotel
where city_id = 1
order by dbo.getHotelMinPrice_cap(hotel.id,1,'2001-01-01', '2021-01-01')
如何在 linq 中使用动态排序编写最后一个 SQL 查询?
【问题讨论】:
-
使用函数排序是一种不好的做法。您应该首先优化您的查询。提供你的函数
getHotelMinPrice_cap,以便提供优化方式。 -
select min(room_price.price) from room_price, room_definition where room_price.roomDef_id = room_definition.ID and room_definition.Hotel_id = Hotel_id and room_definition.capacity=capacity and ( room_price.start_date between enter_date and exit_date or room_price .stop_date 在 enter_date 和 exit_date 之间)
-
我要sql函数。
-
该函数返回我在之前的评论中提到的 min(room_price.price)。 room_price 连接到 room_definition 并且房间定义连接到 hotel
标签: c# linq function asp.net-mvc-5 entity-framework-6