Entity Framework Code First Left Join

夙愿已清 提交于 2019-12-04 13:04:25

if I understand correctly, you would like to get, for a particular article (having as id 'articleId), the list of all the tags (not just those it has), and put a "Checked" to true if it does have it, false otherwise. If so, here's the query I would suggest:

var checkedTags= from t in Db.Tags
                 select new CheckedTag
                        {
                            Id = t.id,
                            Name = t.name,
                            PermanentUrl = t.PermanentUrl,
                            Checked = t.Articles.Any(a => a.Id == articleId)
                        };

Hope this helps :)

Edit: replaced "Contains" with "Any". Thanks @Yakimych.

I would suggest one slight improvement on AbdouMoumen's answer. (tested in .Net 4 with EF 4)

I checked with SQL profiler and the statement 'Checked = t.Articles.Any(...)' while it gives the correct results it produces slightly inefficient SQL code.

(NOTE: my code has different entity names but the exact same scenario)

produces this code:

    CASE WHEN ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[LocationFeatures] AS [Extent2]
    WHERE ([Extent1].[FeatureID] = [Extent2].[FeatureID]) AND (1 = [Extent2].[LocationID])
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[LocationFeatures] AS [Extent3]
    WHERE ([Extent1].[FeatureID] = [Extent3].[FeatureID]) AND (1 = [Extent3].[LocationID])
)) THEN cast(0 as bit) END AS [C1]

I tested by changing it to 'Checked = (t.Articles.Any(...)) ? true : false' the resulting data is the same with a slightly better SQL code. this produces:

CASE WHEN ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[LocationFeatures] AS [Extent2]
    WHERE ([Extent1].[FeatureID] = [Extent2].[FeatureID]) AND (1 = [Extent2].[LocationID])
)) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]

p.s. perhaps this should be a comment but I don't yet have privilege to comment, so if I'm abusing this site please advise on the correct method I should follow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!