fares Ayyad
fares Ayyad

Reputation: 333

asp.net/C#: Handle datetime if null using LINQ

I have null values in database specifically for Good Expiry Date, which is the field is:good_expiryDate.

What i want is to handle it in this way: If good_expiryDate is null i want to present it as "" or "-", if it has value it will show the value retrieved from database?

the LINQ query i write is like this, but it return MinValue if good_expiryDate is null(this is what i tried to do).

var query = (from cd in db.CDIndexes
             join gds in db.Goods on cd.cdin_CDIndexID equals gds.good_CDIndexId 
             join itms in db.Items on gds.good_ItemsID equals itms.item_ItemsID

            where
            cd.cdin_CompanyId==c.Comp_CompanyId&&
            (
                gds.good_RemainCBM > 0 ||
                gds.good_RemainWT > 0 ||
                gds.good_RemainPackages > 0 ||
                gds.good_RemainVolumeWT > 0
            )
            &&
            itms.item_ItemsID==customerId

            select new DataItem
            {
                 depNumber=(int)cd.cdin_Serial,
                 ItemDesc=gds.good_Name,
                 gdExpiryDate =(DateTime) gds.good_expiryDate==null?DateTime.MinValue: (DateTime)gds.good_expiryDate,
                 InvoicBalanceUnits = (decimal) gds.good_RemainPackages,
                 WTBal=(decimal)gds.good_RemainWT,
                 VolWT=(decimal)gds.good_RemainVolumeWT
            }
       );
return query.ToList();

Update: good_expiryDate is type of Datetime, nullable in database

Upvotes: 1

Views: 1273

Answers (2)

Mubariz Feyziyev
Mubariz Feyziyev

Reputation: 412

Change gdExpiryDate type to string type and write like this:

    select new DataItem
             {
                 depNumber=(int)cd.cdin_Serial,
                 ItemDesc=gds.good_Name,
                 gdExpiryDate = gds.good_expiryDate == null ? "" :  gds.good_expiryDate.Value.ToString("dd.mm.yyyy"),
                 InvoicBalanceUnits = (decimal) gds.good_RemainPackages,
                 WTBal=(decimal)gds.good_RemainWT,
                 VolWT=(decimal)gds.good_RemainVolumeWT
             }

Upvotes: 0

ViVi
ViVi

Reputation: 4464

Ensure that gdExpiryDate is of type string.

Then change this line

gdExpiryDate =(DateTime) gds.good_expiryDate==null?DateTime.MinValue: (DateTime)gds.good_expiryDate,

to

gdExpiryDate = gds.good_expiryDate==null? "-" : ((DateTime)gds.good_expiryDate).ToString(),

Upvotes: 1

Related Questions