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 the action object and adapts it from the linq object to the act object of the domain object.
As you can see, I've defined an outer artist connection to interact with.
I did this because I always need an act, whether or not it has an artist.
This works really well if the act actually has an artist.
If it doesn't, then the code dies. This is the culprit:
Artist = new Shared.DO.Artist
{
ID = artist.ID,
Name = artist.Name
},
If I remove it, it will be fine. Can I do what I am trying to do?
0
source to share
3 answers
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 displays the Linq Artist view. The constructor can check for null and do all the initialization.
+2
source to share