1

I know why this is happening but can somebody help me in the right direction of syntax? Currently I have three tables joined by one to one optional relationship. And I joined them as left outer join. My query is....

var model = from t1 in db.Doctors
            join d in db.DoctorAddress on t1.DoctorId equals  d.DoctorId into listi
            join dc in db.DoctorCharges on t1.DoctorId equals dc.DoctorId into listj
            join da in db.DoctorAvailablities on t1.DoctorId equals da.DoctorId into listk
            from d in listi.DefaultIfEmpty()
            from dc in listj.DefaultIfEmpty()
            from da in listk.DefaultIfEmpty()
            select new
            {
                Name = t1.Name,
                RoomNo = da.RoomNo,
                IPDCharge = dc.OPDCharge,
                Address = d.Address,
            };

My problem is that OPDCharge is of type Decimal(not null)

The error I get is:

Exception Details: System.InvalidOperationException: The cast to value type 'Double' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

What would be the correct syntax?

6
  • What datatypes are dc.OPDCharge and IPDCharge? Also what is the datatype of the column in the database? Commented Aug 14, 2013 at 15:48
  • IPDCharge = dc.OPDCharge ?? 0; Perhaps. Commented Aug 14, 2013 at 15:50
  • Column OPDCharge is of Decimal type. Commented Aug 14, 2013 at 16:07
  • @Jaan, are you sure? Does it allow nulls? Commented Aug 14, 2013 at 16:15
  • 1
    @gunr2171 No it does not allow nulls. Commented Aug 14, 2013 at 16:18

3 Answers 3

1

I think an explicit cast to a nullable should do it:

IPDCharge = (decimal?)dc.OPDCharge

But the error message suggest that the type of OPDCharge is actually double, so maybe cast to double? instead?

Sign up to request clarification or add additional context in comments.

1 Comment

@gunr2171 but IPDCharge is in an anonymous type an has the same type as the target.
1

If you want to accept null as being 0 then try:

IPDCharge = dc.OPDCharge ?? 0;

More info: http://msdn.microsoft.com/en-us/library/ms173224.aspx

Comments

0

Try with

IPDCharge = dc.OPDCharge.GetValueOrDefault(0)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.