0

我有两个数据库表(与关系 1:m 连接):

位置 (locId, locName)
1, USA
2, Germany
3, Spain

子位置 (subLocId, subLocName, locId)
1, 丹佛, 1
2, 底特律, 1
3, 纽约, 1
4, 汉堡, 2
5, 柏林, 2
6, 慕尼黑, 2
7, 马德里, 3
8, 巴塞罗那, 3
9 , 瓦伦西亚, 3

使用 Linq to Sql,我需要填写 LocationDto,如下所示: LocationDto (locId, subLocId, name)
1, null, USA
1, 1, Denver
1, 2, Detroit
1, 3, New York
2,null, Germany
2, 4, 汉堡
2, 5, 柏林
2, 6, 慕尼黑
3,null, 西班牙
3, 7, 马德里
3, 8, 巴塞罗那
3, 9, 瓦伦西亚

4

1 回答 1

1

创建一个新类来保存连接的对象:

public class JoinedLocations
{
    public int locId{get;set;}
    public int? subLocId{get;set;}
    public string Description{get;set;}
}

然后运行此查询

var query = 
Location
.GroupJoin
(
    Sublocations.DefaultIfEmpty(),
    l=>l.locId,
    s=>s.locId,
    (l,s)=>new {l,s}
)
.SelectMany
(
    x=>
    x.s.DefaultIfEmpty
    (
        new Sublocations
        {
            subLocId=-1,
            subLocName="",
            locId=-1
        }
    ),
    (l,s)=> 
    new JoinedLocations
    {
        locId=l.l.locId,
        subLocId=s.subLocId,
        Description = (s.subLocId==-1?l.l.locName:s.subLocName)
    }
)
.Union
(
    loc
    .Select
    (
        x=>
        new JoinedLocations
        {
            locId=x.locId,
            subLocId=null,
            Description = x.locName
        }
    )
)
.OrderBy(x=>x.locId)
.ThenBy (x => x.subLocId)

这会给你你想要的结果。

于 2013-08-22T12:26:23.433 回答