使用LINQ实体框架进行LEFT JOIN或RIGHT JOIN

4
尝试使用Linq进行连接操作。 应该使用左连接还是右连接?
     APPLICANT TABLE                         PROFILE TABLE
APPLICANT_ID|profile_id|Applicant_Name| |profile_id|Applicant_Name  
      1     |    NULL  |  RAY HEAVENS | |    1     | MARK LAPID
      2     |    NULL  |  BEN TULFO   | |    2     | SUPER MAN
      3     |     1    |      NULL    | |    3     | BRANDON KNIGHT
      4     |     2    |      NULL    | |
      5     |     3    |      NULL    | |

DESIRED OUTPUT: 

APPLICANT_ID | Applicant_Name
      1      |   RAY HEAVENS
      2      |   BEN TULFO
      3      |   MARK LAPID
      4      |   SUPERMAN
      5      |   BRANDON KNIGHT

这是我的控制器代码:

这是我的控制器代码:

var applicantList = (from a in context.Profiles 
                     join app in context.APPLICANTs
                     on a.PROFILE_ID equals app.Profile_id into output
                     from j in output.DefaultIfEmpty(new APPLICANT())
                     select j ).Take(1000).AsEnumerable();

                   applicantdata = applicantList.AsQueryable().OrderBy(v => v.APPLICANT_ID).ToList();


            if (applicantdata.Any())
            {
                Cache.Set("applicants", applicantdata, 30);
            }
        }
        return applicantdata;

    }

我希望有人能够推荐给我使用什么或者做什么。 非常感谢。


1
我认为.DefaultIfEmpty()可以翻译成LEFT JOIN,你有对它进行性能分析吗? - Mathieu Guindon
1个回答

8

针对错误更新:您需要创建一个具有所需属性的新类并返回它。

    var applicantList = (from app in context.APPLICANTs
                         join a in context.Profiles
                         on app.Profile_id equals a.PROFILE_ID into output
                         from j in output.DefaultIfEmpty()
                         select new { APPLICANT_ID = app.APPLICANT_ID, Applicant_Name = (j == null ? app.Applicant_Name : j.Applicant_Name) }).Take(1000).AsEnumerable();

1
先生,我现在遇到了异常。Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<Applicant.Models.APPLICANT>'. An explicit conversion exists (are you missing a cast?) 代码位置:applicantdata = applicantList.AsQueryable().OrderBy(v => v.APPLICANT_ID).ToList(); - Enrique Gil
1
@cheedep先生,谢谢您的帮助。但是现在在applicantdata = applicantList.AsQueryable().OrderBy(v => v.APPLICANT_ID).ToList();这行代码中出现了一个新的异常:NotSupported Exception was unhandled by user code The entity or complex type 'Model.APPLICANT' cannot be constructed in a LINQ to Entities query - Enrique Gil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接