0

I have a Linq query like this :

var items = from v in work.GetRepo<VW_V>().Query
        join k in work.GetRepo<K>().Query on v.Loc_Id equals k.Id
        join p in work.GetRepo<P>().Query on v.Peer_Id equals p.Id
        join tt in work.GetRepo<TT>().Query on v.Item_Id equals tt.Id
        select (new MyModel
        {
            Id = v.Id,
            Location = k != null ? k.Name : string.Empty,
            ItemName = tt.Name,
            Peer = p != null ? p.Name : string.Empty,
        });

This query works fine. But I want to have records that some of them don't have a Peer. How can I do that? This query returns records that have only Peers, how can I have records that both have peer and don't have peer. I want to show the Peer's name if peer exists in that record. Thanks.

jason
  • 6,962
  • 36
  • 117
  • 198
  • 2
    It's called outer join. More: http://msdn.microsoft.com/en-us/library/bb397895.aspx –  Sep 30 '14 at 12:59

2 Answers2

1

It is called left outer join. Try:

var items = from v in work.GetRepo<VW_V>().Query
        join k in work.GetRepo<K>().Query on v.Loc_Id equals k.Id
        join p in work.GetRepo<P>().Query on v.Peer_Id equals p.Id into subpeer_j
        from subpeer in subpeer_j.DefaultIfEmpty()
        join tt in work.GetRepo<TT>().Query on v.Item_Id equals tt.Id
        select (new MyModel
        {
            Id = v.Id,
            Location = k != null ? k.Name : string.Empty,
            ItemName = tt.Name,
            Peer = subpeer != null ? subpeer.Name : string.Empty,
        });
1
var items = from v in work.GetRepo<VW_V>().Query

            join k in work.GetRepo<K>().Query 
              on v.Loc_Id equals k.Id

            join p in work.GetRepo<P>().Query 
              on v.Peer_Id equals p.Id
            into pJoinData 
            from pJoinRecord in pJoinData.DefaultIfEmpty( )

            join tt in work.GetRepo<TT>().Query 
              on v.Item_Id equals tt.Id

            select (new MyModel
            {
                Id = v.Id,
                Location = k != null ? k.Name : string.Empty,
                ItemName = tt.Name,
                Peer = pJoinRecord != null ? pJoinRecord.Name : string.Empty,
            });
Viper
  • 2,216
  • 1
  • 21
  • 41