Adding Parameter dynamically to the Entity Framework query

We can pass the parameters dynamically to a entity framework where clause. Below is the code snippet for passing the parameters dynamically...

//Declare the instances for the Entities and ObjectParameter collection
MTEntities objMT = new MTEntities();
List ob = new List();

//Declare the query holder variable
 string strDyn = "";

//Build the query based on the selected used inputs
if(txtName.text !="")
{
 strDyn += "it.Organization =@Organization";
  //Add the object parameter into the collection
  ob.Add(new ObjectParameter("Organization", txtName.Text));
}

if(txtGuide.Text != "")
{
 strDyn = strDyn.Length == 0 ? strDyn + "And" : strDyn;
 strDyn += "it.CityName= @city";
 ob.Add(New ObjectParameter("city", txtCity.Text));
}

// repeat the above if block for all the parameters you need to pass to the query
if (strDyn.Length > 0)
{
if (strDyn.EndsWith("And"))
strDyn = strDyn.Remove(strDyn.Length, -3);  //Removes the Last 'And'
var query = objMT.MT_tblOrganizations.Where(strDyn, ob.ToArray()).Select(O => new { O.CreatedDate, O.OrganizationID, O.Organization, O.Verticals, O.Offerings, O.WebsiteURL});

//Execute and assign the result to the gridview
MyGridview.DataSource = query;
MyGridview.DataBind();
}

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment