实体框架在连接后返回不同的记录

时间:2013-05-28 18:33:21

标签: c# linq entity-framework

考虑我们有这两个实体和一个自定义对象:

    public class  Entiy1
{
    public int Id { get; set; }
    public int DestinationId { get; set; }
    public string Name { get; set; }
    public string JobTitle { get; set; }
}

public class Entiy2
{
    [Key]
    public int DestinationId { get; set; }
    public int DestinationName { get; set; }


}
public class EntityDTO
{
    public int DestinationName { get; set; }
    public int DestinationId { get; set; }
    public string Name { get; set; }
    public string JobTitle { get; set; }
}

数据是这样的:

  

实体1:
Id = 1,DestinationId = 1,Name = Name1,JobTitle = Job1
  Id = 2,DestinationId = 1,Name = Name2,JobTitle = Job2
Id = 3,   DestinationId = 2,Name = Name3,JobTitle = Job3
Id = 4,   DestinationId = 2,Name = Name4,JobTitle = Job4
Id = 5,   目标-ID = 2,名称= NAME5,JOBTITLE =作业5
  实体2:
  DestinationId = 1,DestinationName = Destination1
  DestinationId = 2,DestinationName = Destination2

如何选择不同的destinationId并从Entity1中选择Name和JobTitle然后将它们与Entity2连接以获取目标名称并将它们作为EntityDTO返回?

3 个答案:

答案 0 :(得分:2)

这是一种方法:

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
            } ;

技巧是group by,然后获取分组的第一个元素。这也被称为“与...截然不同”,像MoreLinq这样的库提供了开箱即用的功能。

答案 1 :(得分:1)

使用LINQ扩展,我更喜欢它们:

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
                });

与Gert的anwser真的相同。您可以使用Distinct但是,您必须继承IEquatible<T>并实施Equals方法并覆盖GetHashCode方法才能使用{{1}}方法工作

答案 2 :(得分:0)

您可以像这样使用LINQ join运算符:

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
              };