Entity Framework returning distinct records after join

前端 未结 3 1939
庸人自扰
庸人自扰 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: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 and implement the Equals method and override the GetHashCode method to get it to work.

提交回复
热议问题