[英]Linq query where clause
我正在使用Linq to Entities
并且有类似这样的查询
context.Hotels
.Where(h => h.HotelType.Contains(s.HotelTypeId.ToString()))
.Select(hotel => new Model.Hotel
{
HotelId = hotel.HotelID,
HotelName = hotel.HotelName,
HotelFileName = hotel.HotelFileName,
StarRating = hotel.StarRating,
CountryName = hotel.Country.CountryName,
PlaceName = hotel.Place.PlaceName
})
我在where
子句中使用.ToString()
, where
我使用Linq To Entities
时, where
子句无效。 但是实际上“ HotelType”列的值用竖线字符分隔,例如1 | 2 | 3。.现在,我只想提取那些类型为1的酒店。这怎么可能? 请帮忙
这是一个hack,但它应该可以工作。
Where(h => ("|" + h.HotelType + "|").Contains("|" + s.HotelTypeId.ToString() + "|"))
首先将1|2|3
变成|1|2|3|
然后寻找|1|
或|2|
并且无论ID是第一个还是最后一个,还是中间的某个位置,它都可以工作。
但是您确实应该重组数据库-对这样的信息进行编码通常是一个非常糟糕的主意,并且您已经发现了这一信息,因为您不得不询问如何做一些琐碎的事情。
还值得注意的是,EF 6.1中支持ToString() http://blogs.msdn.com/b/adonet/archive/2014/03/17/ef6-1-0-rtm-available.aspx
context.Hotels
.Where(h => h.HotelType.Split('|').Select(str=>Convert.ToInt32(str)).Contains(s.HotelTypeId))
.Select(hotel => new Model.Hotel
{
HotelId = hotel.HotelID,
HotelName = hotel.HotelName,
HotelFileName = hotel.HotelFileName,
StarRating = hotel.StarRating,
CountryName = hotel.Country.CountryName,
PlaceName = hotel.Place.PlaceName
})
假设您的HotelType
为int
,则可以执行此操作。
context.Hotels
.Where(h => h.HotelType.Split("|").Select(ht=>int.Parse(ht))
.Contains(s.HotelTypeId))
.Select(hotel => new Model.Hotel
{
HotelId = hotel.HotelID,
HotelName = hotel.HotelName,
HotelFileName = hotel.HotelFileName,
StarRating = hotel.StarRating,
CountryName = hotel.Country.CountryName,
PlaceName = hotel.Place.PlaceName
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.