实体& LINQ方法链查询

时间:2011-01-27 20:19:34

标签: c# linq entity-framework

好的,我们可以说下面是我导入实体模型的数据库结构:

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

所有工作除了星期几行外。

3 个答案:

答案 0 :(得分: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进行评估。

答案 1 :(得分: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;
            }
        }

我发现了,这很有效!

答案 2 :(得分:0)

我认为你的意思是问号:

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

等等......