2011-01-27 48 views
0

好吧,让说,下面是我所导入的实体模型我的数据库结构:实体LINQ法的连锁查询

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 

在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; 
      } 
     } 

除了星期几线以外的所有作品。

回答

1
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; 
      } 
     } 

我发现,这个作品!

1

你已经接近我认为你是后:

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(); 
     } 
    } 

你可以只保留追加到您的查询。直到实际使用它才会被评估。在这种情况下,将在返回时调用ToList时进行评估。

+0

这项工作? placereturn = placereturn.Where(s => s.Time.Any(t => t.StartTime> = request.StartTime.Value)); – Cyberdrew 2011-01-27 20:37:47

+0

我知道我忘了placereturn = placereturn。 DOH!我正在写在记事本中。 – Cyberdrew 2011-01-27 20:38:25

0

我想你所指的问号:

if (request.StartTime.HasValue) 
      placereturn.Where(r => r.StartTime >= DateTime.Now); 

等等......