0

Using some logic mentioned in this answer, I'm using this code to perform outer joins on a few tables. I know that one of the three joins will yield a MyField value. However, in my select statement, I'm calling a constructor, and I only want to use the MyField value that is not null.

public static MyResult GetMyResult(string MyString)
{
    var result = (from w in context.TABLE_ONEs
        from a in context.TABLE_TWOs.Where(x => x.field1 == w.field1).DefaultIfEmpty()
        from l in context.TABLE_THREEs.Where(y => y.field1 == w.field1).DefaultIfEmpty()
        from n in context.TABLE_FOURs.Where(z => z.field1 == w.field1).DefaultIfEmpty()
        select new MyResult(w.someField, 
            w.someOtherField, 
            (a.date ?? l.date ?? n.date))
        ).First();

        return result;
    }

However, I'm getting compile errors saying, "Operator '??' cannot be applied to operands of type 'System.DateTime' and 'System.DateTime'". This works fine for nullable data-types, such as string, but not on this "date" field.

Do you know of a way to fix this, aside from changing the database column to nullable DateTime?

Community
  • 1
  • 1
WEFX
  • 8,298
  • 8
  • 66
  • 102
  • Wont the **DateTime** field default to **DateTime.MinValue** when it isn't set in the database? In that case something ugly like this would work: **(a.date != DateTime.MinValue ? a.date : (l.date != DateTime.MinValue ? l.date : n.date))** – Thomas C. G. de Vilhena Jul 01 '13 at 00:52
  • @ThomasC.G.deVilhena: I tried this solution and I got System.Reflection.TargetOfInvocationException. – Daniel Gimenez Jul 01 '13 at 00:56

1 Answers1

1

The following isn't quite clean, but should work.

date = (DateTime?) (a != null) ? a.date : (l != null) ? l.date : (n != null) ? n.date : null

Instead of a nullable DateTime you use MinDate so it remains a value type.

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70