使用EF和linq将正确的数据加载到DTO时遇到问题。
从我的数据库中我收到以下示例数据:
1, 1, 1
1, 1, 2
1, 1, 3
2, 1, 4
2, 1, 5
等
我想在DTO中加载这些数据,如下所示:
int, int, ICollection<int>
所以对于示例数据:
new MyDto(1, 1, new List<int> { 1, 2, 3 });
new MyDto(2, 1, new List<int> { 4, 5 });
这是我的linq查询
var result = (from adresses in context.Adress
join person in context.Person on adresses.PersonId equals person.Id
select new MyObj { Id1 = adresses.Id1, Id2 = adresses.Id2, PersonId = person.Id })
但这是错误的,因为它没有按Id1和Id2分组,也没有将personIds放在列表中......
请告诉我如何实现这一目标?
答案 0 :(得分:1)
使用Linq进行数据透视是一种更好的方法。你可以看一下这个链接:
Is it possible to Pivot data using LINQ
要回答您的问题,以下是一个示例:
var result = (from adresses in context.Adress
join person in context.Person on adresses.PersonId equals person.Id
group address by address.Id1 into gResult
select new{
Id1 = gResult.Key,
Id2 = gResult.Select(r => r.Id2).FirstOrDefault (),
Id3 = gResult.Select (r => r.Id3)
});
答案 1 :(得分:0)
在您的Address类中,您是否拥有Person实例的属性,以便您能够在这两个类之间建立关系?如果是这样,以下查询可能会为您提供您正在寻找的结果集:
public class Address
{
public int Id1 { get; set; }
public int Id2 { get; set; }
public virtual Person Person { get; set; }
}
public void Foo()
{
IEnumerable<MyObj> = context.Address.Select(x => new {
Id1 = x.Id1,
Id2 = x.Id2,
PersonId = x.Person.Id
});
}
答案 2 :(得分:0)
感谢你们的好答案,我终于可以解决了: - )
var result = from tuple in (from address in context.Adresses
join person in context.Persons on address.PersonId equals person.Id
select new { person.Id, address.Id1, address.Id2})
group tuple by new { tuple.Id1, tuple.Id2 } into myGrouping
select
new MyObj
{
Id1 = myGrouping.Key.Id1,
Id2 = myGrouping.Key.Id2,
PersonIds = myGrouping.Select(x => x.PersonId).Distinct()
};