Entity Framework returning distinct records after join

前端 未结 3 1940
庸人自扰
庸人自扰 2021-01-27 15:37

Consider we have these two entities and one custom object :

    public class  Entiy1
{
    public int Id { get; set; }
    public int DestinationId { get; set;          


        
3条回答
  •  粉色の甜心
    2021-01-27 16:17

    Here's a way to do it:

    var query = from e1 in
        (from e1 in entities1
            group e1 by e1.DestinationId into grp
            select grp.First())
        join e2 in entities2 on e1.DestinationId equals e2.DestinationId
        select new EntityDTO 
                { 
                    DestinationId = e1.DestinationId, 
                    DestinationName = e2.DestinationName,
                    Name = e1.Name,
                    JobTitle = e1.JobTitle
                } ;
    

    The trick is the group by and then taking the first element of the grouping. This is also referred to as "distinct by" that a library like MoreLinq provides out of the box.

提交回复
热议问题