iasksillyquestions
iasksillyquestions

Reputation: 5689

Outer Joins and Linq

So I have the following code:

  return from a in DBContext.Acts
         join artist in DBContext.Artists on a.ArtistID equals artist.ID into art
         from artist in art.DefaultIfEmpty()

         select new Shared.DO.Act
         {
             ID = a.ID,
             Name = a.Name,
             Artist = new Shared.DO.Artist
             {
                 ID = artist.ID,
                 Name = artist.Name
             },
             GigId = a.GigID
         };

This loads an act object and adapts it from a linq object to my domain act object.

As you can see I have defined an outer join on the artist to act relationship.

I have done this because I always want the act, irrespective of if it has an artist.

This works really well if the act does indeed have an artist.

If it doesnt then the code dies. This is the the culprit:

 Artist = new Shared.DO.Artist
          {
              ID = artist.ID,
              Name = artist.Name
          },

If I remove it, its fine. Is it possible to do what I'm attempting?

Upvotes: 0

Views: 966

Answers (3)

iasksillyquestions
iasksillyquestions

Reputation: 5689

Actually... this seems the best answer for me....

Artist = artist == null ? null : new Shared.DO.Artist
                    {
                       ID =  artist.ID,
                       Name = artist.Name
                    },

Upvotes: 1

user1228
user1228

Reputation:

           Artist = new Shared.DO.Artist
           {
               ID = artist == null ? Guid.NewGuid() : artist.ID,
               Name = artist == null ? string.Empty : artist.Name
           }

Alternatively, add a constructor to Shared.DO.Artist that takes the Linq representation of Artist. The constructor can check for null and perform all initialization.

Upvotes: 2

Filip Ekberg
Filip Ekberg

Reputation: 36287

You want to create a new object, by calling the constructor. Remove Artist = and then replace { } with ().

Upvotes: 0

Related Questions