ASP.NET Core & EntityFramework Core: Left (Outer) Join in Linq

后端 未结 3 1855
清歌不尽
清歌不尽 2020-12-01 15:58

I am trying to get a left join working in Linq using ASP.NET Core and EntityFramework Core.

Simple situation with two tables:

    Person (id, firstname, lastnam
3条回答
  •  悲哀的现实
    2020-12-01 16:41

    You not doing left join, the linq which you are using is basically creating a inner join. For left join in linq use into keyword

    [HttpGet]
    public IActionResult Get()
    {
        var result = from person in _dbContext.Person
                        join detail in _dbContext.PersonDetails on person.Id equals detail.PersonId  
                        into Details
                        from defaultVal in Details.DefaultIfEmpty()
                        select new
                        {
                            id = person.Id,
                            firstname = person.Firstname,
                            lastname = person.Lastname,
                            detailText = defaultVal.DetailText
                        };
       return Ok(result);
    }
    

提交回复
热议问题