如何为 sql 编写 lambda (linq) 表达式?
Posted
技术标签:
【中文标题】如何为 sql 编写 lambda (linq) 表达式?【英文标题】:How to write lambda (linq) expression for sql? 【发布时间】:2013-05-23 09:08:36 【问题描述】:我有一个 Sql 语句,我需要为其生成相应的 Lambda 表达式 (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】:假设数据上下文在变量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
【讨论】:
以上是关于如何为 sql 编写 lambda (linq) 表达式?的主要内容,如果未能解决你的问题,请参考以下文章
如何为CriteriaOperator过滤对象转换为lambda表达式,即:linq to xpo的动态where语句
如何为实体框架 Sql 提供程序编写测试并访问生成的 Sql 命令
如何为 API Gateway Websocket 编写 Java Lambda 处理程序?