如何为sql编写lambda(linq)表达式?

时间:2013-05-23 09:08:37

标签: linq linq-to-sql lambda sql-to-linq-conversion

我有一个Sql语句,我需要生成相应的Lambda Expression(Linq)。 这是SQL

Declare @CurrentUserId as int
Declare @CurrentDate as datetime
Set @CurrentDate = GetDate()
Set @CurrentUserId = 1

Select C.conferenceId,C.specialtyId,C.name,C.city,S.abbr as statebbbr,CTRY.name as countryname,C.startdate,C.enddate
from Conferences C
Inner join (
    Select distinct SpecialtyId 
    from UserContent
    Where UserId = @CurrentUserId and DeletedFlag = 0
    ) DT on C.SpecialtyId = DT.SpecialtyId
Left outer join State S on C.StateId = S.StateId
Inner join Country CTRY on C.CountryId = CTRY.CountryId
Where C.DisplayStartDate <= @CurrentDate 
    and C.DisplayEndDate >= @CurrentDate
    and C.DeletedFlag = 0
    and C.Publish = 1
Order by C.startdate ASC

这是什么lambda(linq)表达式?

1 个答案:

答案 0 :(得分:1)

假设数据上下文位于变量context

from c in context.conferences
join ctry in context.country on c.CountryId equals ctry.CountryId
join s1 in context.State on c.StateId equals s.StateId into s2
from s in s2.DefaultIfEmpty()
where
  c.DisplayStartDate <= System.DateTime.Now
  && c.DisplayEndDate >= System.DateTime.Now
  && c.DeletedFlag == 0 // or false if represented as a bool
  && c.Publish == 1 // or true if represented as a bool
  && context.UserContent.Any(
                              x => x.SpecialityId == c.specialityId 
                              && x.UserId == currentUserId
                              && x.DeletedFlag == 0 
                              // or if represented as a bool "&& !x.DeletedFlag"
                              )
select new {
      c.ConferenceId,
        c.SpecialtyId,
        c.name,
        c.city,
        stateabbr = s.abbr,
        countryname = ctry.name,
        c.startdate,
        c.enddate
}