开发者

How to convert this SQL query to LINQ or Lambda expression?

I have the following SQL query:

SELECT C.ID, C.Name FROM Category C JOIN Layout L ON C.ID = L.CategoryID
JOIN Position P ON L.PositionID LIKE '%' + CAST(P.ID AS VARCHAR) + '%'
WHERE P.Code = 'TopMenu'

and following data

Position:

ID      Code

1       TopMenu
2       BottomMenu

Category

ID      Name

1       Home
2       Contact
3       About

Layout

ID      CategoryID     PositionID
1       1              1
2       2              1,2
3       3           开发者_如何学Python   1,2

With the above data, is it possible to convert the SQL query to LINQ or Lambda expression?

Any help is appreciated!


This might do what you want:

Layout
    .Where(x => Position
        .Where(y => y.Code == "TopMenu")
        .Select(y => SqlClient.SqlMethods.Like(x.PositionID, "%" + y.ID.ToString() + "%")
        ).Count() > 0
    ).Join(
        Category,
        x => x.CategoryID,
        x => x.ID,
        (o,i) => new { ID = i.ID, Name = i.Name }
    )

Although you might want to materialize the 'Position' sub query to save on time like so:

var innerSubQuery = Position.Where(y => y.Code == "TopMenu");

Layout
    .Where(x => innerSubQuery
        .Select(y => SqlClient.SqlMethods.Like(x.PositionID, "%" + y.ID.ToString() + "%")
        ).Count() > 0
    ).Join(
        Category,
        x => x.CategoryID,
        x => x.ID,
        (o,i) => new { ID = i.ID, Name = i.Name }
    );

I do, however, agree with Jon that to really make your life simpler you should change the way you're handling the many-to-many relationship by creating a 'Layout_Position' table.


Well, you won't be able to express the second join as a join, because it's not an equijoin, but this should do it:

from c in category
join l in layout on c.Id equals l.CategoryId
from p in position
where p.Id.Contains(l.PositionId)
select new { c.Id, c.Name };

Note that your "contains/LIKE" clause will give you bad results when you've got more than 9 positions. There are better approaches to many-to-many relations than using a comma-separated list. (Such as an intermediate table.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜