我是实体框架和linq的新手。我正在使用asp.net mvc 5和C#。 我写的动态排序查询,如下所示:实体框架linq orderby函数
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) 从room_price,room_definition 其中room_price.roomDef_id = room_definition.ID 和room_definition.Hotel_id = HOTEL_ID和room_definition.capacity =容量 之间enter_date和exit_date或room_price.stop_date之间(room_price.start_date enter_date和exit_date) – saeedeh
我正在询问sql函数。 –