Entity Framework returning distinct records after join

前端 未结 3 1938
庸人自扰
庸人自扰 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:15

    You can use the LINQ join operator like this:

    var results = from e1 in context.Entity1s
                  join e2 in context.Entity2s
                  on e1.DestinationId equals e2.DestinationId
                  select new EntityDTO
                  {
                      DestinationId = e1.DestinationId,
                      Name = e1.Name,
                      JobTitle = e1.JobTitle,
                      DestinationName = e2.DestinationName
                  };
    
    0 讨论(0)
  • 2021-01-27 16:16

    Using LINQ extensions, I'm more of a fan of them:

    var results = entityList1
                .GroupBy(e => e.DestinationId)
                .Select(e => e.First())
                .Join(entityList2, e1 => e1.DestinationId, e2 => e2.DestinationId, (e1, e2) => 
                    new EntityDTO
                    {
                        DestinationId = e1.DestinationId,
                        DestinationName = e2.DestinationName,
                        JobTitle = e1.JobTitle,
                        Name = e1.Name
                    });
    

    Same thing as Gert's anwser really. You can use Distinct but, you would have to inherit from IEquatible<T> and implement the Equals method and override the GetHashCode method to get it to work.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题