C dotnet Linq Adds a Condition if Not Empty Value

To remind me

This post contains a custom LINQ database query that will includes conditions if there are exist variables and ignores conditions on empty variables.

Following is an example in one method:


/* returning json value
 * with three conditions : vesselId, portCode, filterYear
 */

public JsonResult GetEvents(Decimal? vesselId, string portCode, string filterYear)
        {
            using (dbEntities dc = new dbEntities()) //define entities
            {
                var events = new List(); //define variable on searching table


                if(vesselId == 0) { vesselId = null; } //state variable condition to null value
                if (portCode.Equals("0")) { portCode = null; }//state variable condition to null value

                var qry = from sched in dc.TABLE select sched; //starting query

                if (vesselId != null) //state first condition if not null
                {
                    qry = qry.Where(n => n.VSL_ID== vesselId);
                }
                if ( !String.IsNullOrEmpty(portCode))//state second condition if not null
                {
                    qry = qry.Where(n => n.PORT.Equals(portCode));
                }
                if (!String.IsNullOrEmpty(filterYear))//state third condition if not null
                {
                    qry = qry.Where(n => n.YEAR.Equals(filterYear));
                }

                events = qry.ToList();


                return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; // returning as json value
            }
        }
That's it,,

Tidak ada komentar:

Posting Komentar