[英]Entity & LINQ Method Chain Query
Ok, lets say that below is my database structure that I have imported into an Entity Model: 好的,可以说以下是我导入到实体模型中的数据库结构:
Place
----------------
Id bigint PK
Name varchar(10)
Time
----------------
Id bigint PK
PlaceId bigint FK_Place_Id
StartTime datetime
EndTime datetime
DayOfWeek
----------------
Id bigint PK
Name varchar(10)
TimeDayOfWeek
----------------
TimeId bigint PK FK_Time_Id
DayOfWeekId bigint PK FK_DayOfWeek_Id
In a LINQ method chain I would like to do something similar to the following: 在LINQ方法链中,我想做类似以下的事情:
public List<Place> GetPlaces(SearchRequest request)
{
using(var c = new Context())
{
var placereturn = c.Places.AsEnumerable();
if (request.StartTime.HasValue)
placereturn = c.Places.Where(s => s.Time.Any(t => t.StartTime >= request.StartTime));
if (request.EndTime.HasValue)
placereturn = c.Places.Where(s => s.Time.Any(t => t.EndTime >= request.EndTime));
if (request.DayOfWeek.HasValue)
placereturn = c.Places.Where(s => s.Time.Any(t => t.DayOfWeeks.Any(z => z.Day = request.DayOfWeek)));
return placereturn;
}
}
All works except for the Day Of Week line. 除“星期几”行外的所有作品。
You're close already to what I think you are after: 你已经接近我的想法了:
Public List<Place> GetPlaces(SearchRequest request)
{
using(var c = new Context())
{
var placereturn = c.Places;
if (request.StartTime.HasValue)
placereturn = placeretun.Where(???); //Any place that has a start time greater than or equal to the search start time
if (request.EndTime.HasValue)
placereturn = placeretun.Where(???);//Any place that has a end time less than or equal to the search end time
if (request.DayOfWeek.HasValue)
placereturn = placeretun.Where(???);//Any place where the day of week = the search day of week
return placereturn.ToList();
}
}
You can just keep appending to your query. 您可以继续追加您的查询。 It won't be evaluated until it is actually used.
在实际使用之前不会对其进行评估。 In this case, it will be evaluated when you call ToList on the return.
在这种情况下,将在返回时调用ToList进行评估。
public List<Place> GetPlaces(SearchRequest request)
{
using (var c = new Context())
{
var placereturn = c.Places.AsEnumerable();
if (request.StartTime.HasValue)
placereturn = c.Places.Where(s => s.Time.Any(t => t.StartTime >= request.StartTime));
if (request.EndTime.HasValue)
placereturn = c.Places.Where(s => s.Time.Any(t => t.EndTime >= request.EndTime));
if (request.DayOfWeek.HasValue)
placereturn = c.Places.Where(s => s.Time.Any(t => t.DayOfWeeks.Any(z => z.Name == request.DayOfWeek.Value)));
return placereturn;
}
}
I found it, this works! 我找到了,这可行!
I think you mean the question marks: 我想你的意思是问号:
if (request.StartTime.HasValue)
placereturn.Where(r => r.StartTime >= DateTime.Now);
And so on... 等等...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.