转换器sql查询到Linq

时间:2012-03-14 21:01:51

标签: linq-to-sql subquery

我需要将此sql查询转换为linq to sql,结果返回一个IEnumerable:

select VisualAidName, v.VisualAidID, vs.VisualAidStatusName,
    br.BrandName, v.IsEnabled, v.VisualAidCode, v.DateApproved,
    br.BrandID, type,  UserFirstName+ ' ' + UserLastName as name, AreaID
from VisualAids v inner join VisualAidStatus vs 
        on v.VisualAidStatusId = vs.VisualAidStatusId 
    inner join brands br 
        on v.BrandID = br.BrandId 
    inner join VisualAids_Areas_Link vareas 
        on v.VisualAidID = vareas.VisualAidID 
    left join users us 
        on v.Owner = us.UserID  
where
AreaID IN (
    select areaid 
    from Users inner join Users_Area_Link 
        on Users.UserID = Users_Area_Link.UserID 
    where Users.UserID= 3
)

我这样做了:

IEnumerable<Visual_Aid> visualAll = from v in Context.VisualAids
   join vs in Context.VisualAidStatus on v.VisualAidStatusId equals vs.VisualAidStatusId
   join br in Context.Brands on v.BrandID equals br.BrandId
   join us in Context.Users on v.Owner equals us.UserID into vadis
   from x in vadis.DefaultIfEmpty()
   select new Visual_Aid()
   {
       VisualAid_Name = v.VisualAidName,
       VisualAid_Id = v.VisualAidID,
       VisualAid_StatusName = vs.VisualAidStatusName,
       VisualAid_BrandsName = br.BrandName,
       VisualAid_IsEnabled = bool.Parse(v.IsEnabled.ToString()),
       VisualAid_Code = v.VisualAidCode,
       VisualAid_DateApp = v.DateApproved.ToString() ?? "",
       VisualAid_BrandId = int.Parse(v.BrandID.ToString()),
       VisualAid_Type = v.Type,
       VisualAid_Owner = x.UserID == null ? "" : x.UserFirstName + " " + x.UserLastName
   };

但我需要做子查询的一部分,即我需要包含这个:

where AreaID IN (
    select areaid from Users inner join Users_Area_Link
        on Users.UserID = Users_Area_Link.UserID where Users.UserID= 3
)

有人知道吗?非常感谢你提前

1 个答案:

答案 0 :(得分:0)

您可以将其添加为where语句:

.......
join us in Context.Users on v.Owner equals us.UserID into vadis
from x in vadis.DefaultIfEmpty()
where (
        from user in Context.Users
        join userArea in Users_Area_Link
            on user.UserID equals userArea.UserID
        where user.UserID==3
        select userArea.areaid 
       ).Contains(????.AreaID)
select new Visual_Aid()
{
.......