views:

574

answers:

3

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?

A: 

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

Filip Ekberg
How will my Artist object be populated? The Artist object in question is not the generated Linq object. Its actually my domain object!
ListenToRick
+2  A: 
           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.

Will
Actually, the Artist object itself should be the null. It doesnt seem to me to be meaningfull for a Artist object to be "faked". Is there a way to say either, build the Artist object or ... dont?
ListenToRick
+1  A: 

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

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