Reputation: 3393
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?
Upvotes: 1
Views: 135
Reputation: 1657
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
Upvotes: 1
Reputation: 8868
Try with
IPDCharge = dc.OPDCharge.GetValueOrDefault(0)
Upvotes: 0
Reputation: 46947
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?
Upvotes: 1